<?php

declare(strict_types=1);

final class MyronUploadAudioTranscriptAction implements MyronAction
{
    public function __construct(private readonly MyronMediaAccessibilityActionService $service)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/files/audio/{fileId}/transcript',
            method: 'PUT',
            domain: 'content',
            resource: 'audio-transcript',
            verb: 'upload',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'fileId' => ['type' => 'string'],
                    'filename' => ['type' => 'string'],
                    'contentType' => ['type' => 'string'],
                    'contentBase64' => ['type' => 'string'],
                    'sizeBytes' => ['type' => 'integer'],
                    'sha256' => ['type' => 'string'],
                    'metadata' => ['type' => 'object'],
                ],
                'required' => ['fileId', 'filename', 'contentType', 'contentBase64', 'sizeBytes', 'sha256'],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Upload or replace a transcript for an audio asset.',
            sideEffects: ['uploads transcript file', 'writes media_accessibility_attachments'],
            preconditions: ['audio file exists', 'transcript file is .vtt, .srt, or .txt'],
            postconditions: ['audio asset has a transcript attachment'],
            audienceClass: 4,
            adminAliases: ['upload-audio-transcript'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $metadata = is_array($input['metadata'] ?? null) ? (array) $input['metadata'] : [];
            return MyronActionResult::ok($this->service->uploadAudioTranscriptFromEnvelope((string) ($input['fileId'] ?? ''), $input, $metadata, $caller));
        } catch (MyronJsonContentEnvelopeError|InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
