<?php

declare(strict_types=1);

/**
 * APO-218 Card 1 — Return the current design state as a structured JSONM payload.
 *
 * URI:   GET /api/v1/design/definitions/export-current
 * Scope: design.read  · exposeToMcp:TRUE
 *
 * Returns the full JSONM document as structured JSON data (not a file download),
 * enabling AI agents to read the current design system and translate it for
 * external AI design tools (Figma Make, Google Stitch, Claude Design).
 */
final class MyronExportCurrentDefinitionAction implements MyronAction
{
    public function __construct(
        private readonly MyronDefinitionsActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/definitions/export-current',
            method:        'GET',
            domain:        'design',
            resource:      'definition',
            verb:          'export-current',
            inputSchema:   ['type' => 'object', 'properties' => []],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'definition' => ['type' => 'object', 'description' => 'Full JSONM design system payload — schemaVersion, format, id, name, tokens, fontRoles, and all design settings.'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_READ,
            summary:         'Export the current applied design system as a structured JSONM payload. Returns the full token vocabulary, font roles, and design settings as a JSON object ready for translation to external design tools (Figma, Stitch, Claude Design) or round-trip import via POST /api/v1/design/definitions/import.',
            sideEffects:     [],
            preconditions:   ['a valid JSONM design system is currently applied'],
            postconditions:  [],
            audienceClass:   2,
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            // DesignSystemRegistry is loaded by bootstrap's app-local JSONM runtime.
            $registry = new \DesignSystemRegistry();
            if (method_exists($registry, 'ensureStorage')) {
                $registry->ensureStorage();
            }

            $current = (array) $registry->currentDefinition();
            $definition = $registry->exportCurrentDefinition(
                (string) ($current['id'] ?? ''),
                (string) ($current['name'] ?? '')
            );

            return MyronActionResult::ok(['definition' => $definition]);
        } catch (Throwable $e) {
            return MyronActionResult::error('export_failed', $e->getMessage());
        }
    }
}
