<?php

declare(strict_types=1);

final class MyronGetSiteCustomCssChunkAction implements MyronAction
{
    private const MAX_CHUNK_BYTES = 48_000;

    public function __construct(private readonly MyronCustomCssRepository $repository)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/custom-css/site/chunk',
            method: 'GET',
            domain: 'design',
            resource: 'custom-css',
            verb: 'get-chunk',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'offset' => ['type' => 'integer'],
                    'length' => ['type' => 'integer'],
                ],
                'required' => [],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::DESIGN_READ,
            summary: 'Read a bounded chunk of the site custom CSS body.',
            sideEffects: [],
            preconditions: [],
            postconditions: [],
            audienceClass: 4,
            adminAliases: [],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $css = $this->repository->siteCss();
        $offset = max(0, (int) ($input['offset'] ?? 0));
        $length = (int) ($input['length'] ?? self::MAX_CHUNK_BYTES);
        if ($length <= 0 || $length > self::MAX_CHUNK_BYTES) {
            $length = self::MAX_CHUNK_BYTES;
        }
        $totalBytes = strlen($css);

        return MyronActionResult::ok([
            'offset' => $offset,
            'length' => min($length, max(0, $totalBytes - $offset)),
            'totalBytes' => $totalBytes,
            'sha256' => hash('sha256', $css),
            'chunk' => substr($css, $offset, $length),
            'nextOffset' => min($totalBytes, $offset + $length),
            'complete' => $offset + $length >= $totalBytes,
        ]);
    }
}
