<?php

namespace App\Filament\Pages;

use Filament\Pages\Page;
use Illuminate\Support\Facades\Route;
use UnitEnum;
use BackedEnum;
use App\Services\ApiDocumentation;

class ApiCatalog extends Page
{
    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-document-text';

    protected static ?string $navigationLabel = 'API 文档';

    protected static UnitEnum|string|null $navigationGroup = 'API 管理';

    protected static ?int $navigationSort = 1;

    protected string $view = 'filament.pages.api-catalog';

    public array $apiGroups = [];

    public function mount(): void
    {
        $this->apiGroups = $this->buildFromRoutes();
    }

    private function buildFromRoutes(): array
    {
        $routes = Route::getRoutes();
        $groups = [];
        $docs = ApiDocumentation::all();

        foreach ($routes as $route) {
            $uri = $route->uri();
            if (!str_starts_with($uri, 'api/')) {
                continue;
            }

            $methods = array_values(array_filter($route->methods(), fn ($method) => $method !== 'HEAD'));
            $path = '/' . $uri;
            $groupName = $this->resolveGroupName($uri);
            $tag = $this->resolveTag($route, $uri);
            $apiDoc = $docs[$uri] ?? null;

            foreach ($methods as $method) {
                $methodDoc = $apiDoc[$method] ?? null;

                // 获取参数信息
                $params = $this->buildParamHint($uri, [$method]);

                // 获取响应示例
                $responseExamples = [];
                if ($methodDoc) {
                    if (isset($methodDoc['response'])) {
                        $responseExamples = $methodDoc['response'];
                    }
                }

                // 获取详细信息
                $details = [
                    'route_name' => $route->getName(),
                    'action' => $route->getActionName(),
                    'summary' => $methodDoc['summary'] ?? '',
                    'description' => $methodDoc['description'] ?? '',
                    'param_details' => $methodDoc['params'] ?? [],
                    'response_examples' => $responseExamples,
                    'examples' => $methodDoc['examples'] ?? [],
                ];

                $groups[$groupName]['name'] = $groupName;
                $groups[$groupName]['items'][] = [
                    'method' => $method,
                    'path' => $path,
                    'uri' => $uri,
                    'params' => $params,
                    'tag' => $tag,
                    'doc' => $methodDoc,
                    'details' => $details,
                ];
            }
        }

        ksort($groups);

        return array_values($groups);
    }

    private function resolveGroupName(string $uri): string
    {
        $map = [
            'api/questions' => '题库核心 API',
            'api/papers' => '题库核心 API',
            'api/knowledge-mastery' => '知识点掌握 API',
            'api/mistake-book' => '错题本 API',
            'api/analytics' => '错题本 API',
            'api/intelligent-exams' => '智能出卷与学情报告',
            'api/exam-analysis' => '智能出卷与学情报告',
            'api/textbooks' => '教材 API',
            'api/mathrecsys' => 'MathRecSys 集成 API',
            'api/knowledge' => '知识点与能力 API',
            'api/knowledge-points' => '知识点与能力 API',
        ];

        foreach ($map as $prefix => $name) {
            if (str_starts_with($uri, $prefix)) {
                return $name;
            }
        }

        if (str_starts_with($uri, 'api/ocr') || str_contains($uri, 'callback')) {
            return '回调与内部 API';
        }

        if (str_contains($uri, 'test')) {
            return '测试 API';
        }

        return '其他 API';
    }

    private function resolveTag(\Illuminate\Routing\Route $route, string $uri): ?string
    {
        $middleware = (array) $route->middleware();
        if (in_array('internal.token', $middleware, true)) {
            return 'internal';
        }

        if (str_contains($uri, 'test')) {
            return 'test';
        }

        return null;
    }

    private function buildParamHint(string $uri, array $methods): string
    {
        preg_match_all('/\{([^}]+)\}/', $uri, $matches);
        $pathParams = $matches[1] ?? [];

        $parts = [];
        if (!empty($pathParams)) {
            $parts[] = 'path: ' . implode(', ', $pathParams);
        }

        $hasBody = array_intersect($methods, ['POST', 'PUT', 'PATCH']);
        if ($hasBody) {
            $parts[] = 'body: payload';
        }

        if (empty($parts)) {
            return 'query/body: -';
        }

        return implode(' | ', $parts);
    }

    /**
     * 获取 HTTP 方法颜色样式
     */
    public function getMethodColor(string $method): string
    {
        return ApiDocumentation::getMethodColor($method);
    }
}
