<?php

declare(strict_types=1);

namespace App\Framework\Mcp\Shared\Formatters;

use App\Framework\Mcp\Core\ValueObjects\OutputFormat;

/**
 * JSON Output Formatter
 *
 * Formatiert Daten als JSON mit Pretty Print und Unicode-Unterstützung
 */
final readonly class JsonFormatter implements OutputFormatter
{
    public function format(mixed $data): array
    {
        $jsonOptions = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;

        try {
            $content = json_encode($data, $jsonOptions);

            if ($content === false) {
                throw new \JsonException('JSON encoding failed: ' . json_last_error_msg());
            }

            return [
                'content' => $content,
                'format' => $this->getFormat()->value,
                'mime_type' => $this->getFormat()->getMimeType(),
                'size_bytes' => strlen($content),
                'is_valid' => json_validate($content),
            ];

        } catch (\JsonException $e) {
            return [
                'content' => json_encode(['error' => 'JSON formatting failed: ' . $e->getMessage()]),
                'format' => $this->getFormat()->value,
                'error' => true,
            ];
        }
    }

    public function supports(OutputFormat $format): bool
    {
        return $format === OutputFormat::JSON;
    }

    public function getFormat(): OutputFormat
    {
        return OutputFormat::JSON;
    }

    public function getDescription(): string
    {
        return $this->getFormat()->getDescription();
    }
}
