<?php
/**
 * Script para extrair todos os endpoints da Care API
 * Analisa os ficheiros PHP e extrai informação estruturada dos endpoints
 */

$endpoints_dir = __DIR__ . '/src/includes/endpoints/';
$endpoints_classes = [
    'class-auth-endpoints.php',
    'class-clinic-endpoints.php',
    'class-patient-endpoints.php',
    'class-doctor-endpoints.php',
    'class-appointment-endpoints.php',
    'class-encounter-endpoints.php',
    'class-prescription-endpoints.php',
    'class-bill-endpoints.php'
];

$all_endpoints = [];

foreach ($endpoints_classes as $class_file) {
    $filepath = $endpoints_dir . $class_file;
    if (!file_exists($filepath)) {
        continue;
    }

    $content = file_get_contents($filepath);

    // Extrair nome da classe
    if (preg_match('/class\s+(\w+)/', $content, $matches)) {
        $class_name = $matches[1];
        $entity_name = str_replace(['_Endpoints', '_endpoints'], '', $class_name);
        echo "=== $entity_name ENDPOINTS ===\n";

        // Extrair todas as rotas register_rest_route
        $pattern = '/register_rest_route\s*\(\s*[^,]+,\s*[\'"]([^\'"]+)[\'"][^{]*{[^}]*[\'"]methods[\'"].*?=>[^,\'"]*[\'"]?([^\'",\s}]+)[\'"]?[^}]*}/s';

        if (preg_match_all($pattern, $content, $route_matches, PREG_SET_ORDER)) {
            foreach ($route_matches as $match) {
                $path = $match[1];
                $method = strtoupper(trim($match[2], '"\''));

                // Converter constantes WordPress
                $method = str_replace([
                    'WP_REST_Server::READABLE',
                    'WP_REST_Server::CREATABLE',
                    'WP_REST_Server::EDITABLE',
                    'WP_REST_Server::DELETABLE'
                ], ['GET', 'POST', 'PUT', 'DELETE'], $method);

                echo "  $method $path\n";

                $all_endpoints[] = [
                    'entity' => $entity_name,
                    'method' => $method,
                    'path' => $path,
                    'full_url' => '/wp-json/care/v1' . $path
                ];
            }
        }

        echo "\n";
    }
}

// Gerar resumo
echo "=== RESUMO TOTAL ===\n";
echo "Total de endpoints: " . count($all_endpoints) . "\n";

$by_entity = [];
foreach ($all_endpoints as $endpoint) {
    $by_entity[$endpoint['entity']][] = $endpoint;
}

foreach ($by_entity as $entity => $endpoints) {
    echo "$entity: " . count($endpoints) . " endpoints\n";
}

// Gerar JSON estruturado para documentação
$structured_data = [
    'api_info' => [
        'name' => 'KiviCare REST API',
        'version' => '1.0.0',
        'namespace' => 'care/v1',
        'base_url' => '/wp-json/care/v1'
    ],
    'total_endpoints' => count($all_endpoints),
    'endpoints_by_entity' => $by_entity,
    'all_endpoints' => $all_endpoints
];

file_put_contents(__DIR__ . '/api-endpoints-map.json', json_encode($structured_data, JSON_PRETTY_PRINT));
echo "\nMapa de endpoints guardado em: api-endpoints-map.json\n";