<?php

declare(strict_types=1);

/**
 * APO-193 Card 9 — Get the site-wide custom CSS.
 *
 * URI:   GET /api/v1/design/custom-css/site
 * Scope: design.read
 */
final class MyronGetSiteCustomCssAction implements MyronAction
{
    private const SNAPSHOT_INLINE_CSS_BYTES = 48_000;

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/custom-css/site',
            method:        'GET',
            domain:        'design',
            resource:      'custom-css',
            verb:          'get-site',
            inputSchema:   ['type' => 'object', 'properties' => []],
            outputSchema:  [
                'type' => 'object',
                'properties' => [
                    'css' => ['type' => 'string'],
                    'inline' => ['type' => 'boolean'],
                    'truncated' => ['type' => 'boolean'],
                    'bytes' => ['type' => 'integer'],
                    'sha256' => ['type' => 'string'],
                    'fetch' => ['type' => 'object'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_READ,
            summary:         'Get the site-wide custom CSS layer.',
            sideEffects:     [],
            preconditions:   [],
            postconditions:  [],
            audienceClass:   3,
            adminAliases:    [],
            snapshotInclude: true,
            snapshotKey:     'design.siteCustomCss',
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $css = $this->repository->siteCss();
        $bytes = strlen($css);

        if ($caller->callerType === 'system' && $caller->callerId === 'snapshot-composer' && $bytes > self::SNAPSHOT_INLINE_CSS_BYTES) {
            return MyronActionResult::ok([
                'css' => '',
                'inline' => false,
                'truncated' => true,
                'bytes' => $bytes,
                'sha256' => hash('sha256', $css),
                'fetch' => [
                    'api' => '/api/v1/design/custom-css/site',
                    'tool' => 'design_custom_css_get_site',
                    'chunkTool' => 'design_custom_css_get_chunk',
                ],
            ]);
        }

        return MyronActionResult::ok([
            'css' => $css,
            'inline' => true,
            'truncated' => false,
            'bytes' => $bytes,
            'sha256' => hash('sha256', $css),
        ]);
    }
}
