<?php

declare(strict_types=1);

namespace App\Application\Api;

use App\Framework\Attributes\Route;
use App\Framework\Http\Method;
use App\Framework\Http\Status;
use App\Framework\Markdown\MarkdownRenderer;
use App\Framework\Meta\StaticPageMetaResolver;
use App\Framework\OpenApi\MarkdownGenerator;
use App\Framework\OpenApi\OpenApiContact;
use App\Framework\OpenApi\OpenApiGenerator;
use App\Framework\OpenApi\OpenApiInfo;
use App\Framework\OpenApi\OpenApiLicense;
use App\Framework\Router\ApiRoutes;
use App\Framework\Router\Result\JsonResult;
use App\Framework\Router\Result\ViewResult;

/**
 * Controller for serving Markdown-rendered API documentation
 */
final readonly class MarkdownDocsController
{
    public function __construct(
        private OpenApiGenerator $generator,
        private MarkdownGenerator $markdownGenerator,
        private MarkdownRenderer $markdownRenderer,
    ) {
    }

    #[Route(path: '/api/docs/markdown', method: Method::GET, name: ApiRoutes::DOCS_MARKDOWN)]
    public function showMarkdownDocs(): ViewResult
    {
        try {
            $info = new OpenApiInfo(
                title: 'Michael Schiemer API',
                version: '1.0.0',
                description: 'API documentation for Michael Schiemer\'s custom PHP framework',
                contact: new OpenApiContact(
                    name: 'Michael Schiemer',
                    email: 'contact@michaelschiemer.dev',
                ),
                license: new OpenApiLicense(
                    name: 'MIT',
                    url: 'https://opensource.org/licenses/MIT',
                ),
            );

            $spec = $this->generator->generate($info);
            $markdown = $this->markdownGenerator->generate($spec);

            $html = $this->markdownRenderer->render($markdown, 'api', [
                'title' => 'API Documentation',
                'syntaxHighlighting' => true,
            ]);

            return new ViewResult(
                'markdown',
                new StaticPageMetaResolver(
                    'API Documentation',
                    'Interactive API documentation rendered from Markdown'
                )(),
                [
                    'content' => $html,
                    'debug' => [
                        'markdown_length' => strlen($markdown),
                        'html_length' => strlen($html),
                        'spec_paths_count' => count($spec->paths),
                    ],
                ]
            );
        } catch (\Exception $e) {
            return new ViewResult(
                'markdown',
                new StaticPageMetaResolver(
                    'Error',
                    'Error generating documentation'
                )(),
                [
                    'content' => '<h1>Error</h1><p>' . htmlspecialchars($e->getMessage()) . '</p><pre>' . htmlspecialchars($e->getTraceAsString()) . '</pre>',
                ]
            );
        }
    }

    #[Route(path: '/api/docs/markdown/{theme}', method: Method::GET, name: ApiRoutes::DOCS_MARKDOWN_THEMED)]
    public function showMarkdownDocsWithTheme(string $theme): ViewResult
    {
        $validThemes = ['default', 'github', 'docs', 'api'];
        if (! in_array($theme, $validThemes)) {
            $theme = 'default';
        }

        $info = new OpenApiInfo(
            title: 'Michael Schiemer API',
            version: '1.0.0',
            description: 'API documentation for Michael Schiemer\'s custom PHP framework',
        );

        $spec = $this->generator->generate($info);
        $markdown = $this->markdownGenerator->generate($spec);

        $html = $this->markdownRenderer->render($markdown, $theme, [
            'title' => "API Documentation ({$theme} theme)",
            'syntaxHighlighting' => true,
        ]);

        return new ViewResult(
            'markdown',
            new StaticPageMetaResolver(
                "API Documentation ({$theme} theme)",
                "API documentation with {$theme} styling"
            )(),
            [
                'content' => $html,
            ]
        );
    }

    #[Route(path: '/api/docs/test', method: Method::GET, name: ApiRoutes::DOCS_TEST)]
    public function testMarkdown(): ViewResult
    {
        $testMarkdown = "# Test\n\nThis is a **test** of the markdown renderer.\n\n- Item 1\n- Item 2\n\n```php\necho 'Hello World';\n```";

        $html = $this->markdownRenderer->render($testMarkdown, 'default', [
            'title' => 'Test Page',
        ]);

        return new ViewResult(
            'markdown',
            new StaticPageMetaResolver(
                'Test',
                'Test page'
            )(),
            [
                'content' => $html,
                'test_markdown' => $testMarkdown,
            ]
        );
    }

    #[Route(path: '/api/docs/themes', method: Method::GET, name: ApiRoutes::DOCS_THEMES)]
    public function listThemes(): JsonResult
    {
        return new JsonResult([
            'available_themes' => [
                'default' => '/api/docs/markdown/default',
                'github' => '/api/docs/markdown/github',
                'docs' => '/api/docs/markdown/docs',
                'api' => '/api/docs/markdown/api',
            ],
            'current_endpoints' => [
                'swagger_ui' => '/api/docs',
                'selfhosted' => '/api/docs/selfhosted',
                'markdown' => '/api/docs/markdown',
                'test' => '/api/docs/test',
                'json' => '/api/openapi.json',
            ],
        ], Status::OK);
    }
}
