<?php
/**
 * Generador de Índice Comprimido para unms-swagger.json
 * 
 * USO: php gen_index_unms_swagger.php
 * SALIDA: INDEX_api_unms.md en la raíz del plugin
 * 
 * Reduce ~3MB (750K tokens) → ~15KB (3-4K tokens)
 */

$swaggerPath = __DIR__ . '/../references/unms-swagger.json';
$outputPath  = __DIR__ . '/../../INDEX_api_unms.md';

if (!file_exists($swaggerPath)) {
    die("ERROR: No se encontró unms-swagger.json en: $swaggerPath\n");
}

echo "Leyendo unms-swagger.json (" . round(filesize($swaggerPath) / 1024 / 1024, 2) . " MB)...\n";

$swagger = json_decode(file_get_contents($swaggerPath), true);

if (!$swagger) {
    die("ERROR: No se pudo parsear el JSON. Error: " . json_last_error_msg() . "\n");
}

$paths     = $swagger['paths'] ?? [];
$info      = $swagger['info'] ?? [];
$basePath  = $swagger['basePath'] ?? '';
$host      = $swagger['host'] ?? '';

// Agrupar por tag
$grouped = [];
$tagDescriptions = [];

// Recolectar descripciones de tags
foreach ($swagger['tags'] ?? [] as $tag) {
    $tagDescriptions[$tag['name']] = $tag['description'] ?? '';
}

foreach ($paths as $path => $methods) {
    foreach ($methods as $method => $operation) {
        if (!in_array(strtoupper($method), ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])) continue;

        $tags    = $operation['tags'] ?? ['sin-tag'];
        $summary = $operation['summary'] ?? $operation['description'] ?? '—';
        $opId    = $operation['operationId'] ?? '';

        // Extraer parámetros clave (no el body completo)
        $params = [];
        foreach ($operation['parameters'] ?? [] as $param) {
            if (in_array($param['in'], ['path', 'query'])) {
                $required = ($param['required'] ?? false) ? '' : '?';
                $params[] = $param['name'] . $required;
            }
        }
        $paramStr = $params ? ' [' . implode(', ', $params) . ']' : '';

        // Códigos de respuesta clave
        $responses = array_keys($operation['responses'] ?? []);
        $respStr = $responses ? ' → ' . implode('/', $responses) : '';

        foreach ($tags as $tag) {
            $grouped[$tag][] = sprintf(
                "  - %-8s `%s`%s — %s%s",
                strtoupper($method),
                $path,
                $paramStr,
                $summary,
                $respStr
            );
        }
    }
}

ksort($grouped);

// Generar Markdown
$lines = [];
$lines[] = "# Índice API UNMS (UISP) — NMS v2.1";
$lines[] = "";
$lines[] = "> **Generado automáticamente** desde `unms-swagger.json`";
$lines[] = "> Ejecutar `php .agent/scripts/gen_index_unms_swagger.php` para regenerar.";
$lines[] = "";
$lines[] = "**Host:** `{$host}`  **Base Path:** `{$basePath}`";
$lines[] = "**Versión API:** " . ($info['version'] ?? 'N/A');
$lines[] = "";
$lines[] = "---";
$lines[] = "";
$lines[] = "## Resumen de Grupos";
$lines[] = "";

$total = 0;
foreach ($grouped as $tag => $ops) {
    $count = count($ops);
    $total += $count;
    $desc = $tagDescriptions[$tag] ?? '';
    $lines[] = "- **{$tag}** ({$count} endpoints)" . ($desc ? " — {$desc}" : '');
}
$lines[] = "";
$lines[] = "**Total: {$total} endpoints en " . count($grouped) . " grupos**";
$lines[] = "";
$lines[] = "---";
$lines[] = "";

// Detalle por grupo
foreach ($grouped as $tag => $ops) {
    $desc = $tagDescriptions[$tag] ?? '';
    $lines[] = "## {$tag}" . ($desc ? " — _{$desc}_" : '');
    $lines[] = "";
    foreach ($ops as $op) {
        $lines[] = $op;
    }
    $lines[] = "";
}

$output = implode("\n", $lines);
file_put_contents($outputPath, $output);

$sizeKb = round(strlen($output) / 1024, 1);
$tokenEst = round(strlen($output) / 4);

echo "✅ Índice generado: INDEX_api_unms.md\n";
echo "   Tamaño: {$sizeKb} KB (~{$tokenEst} tokens)\n";
echo "   Reducción: " . round((1 - strlen($output) / filesize($swaggerPath)) * 100) . "% vs swagger original\n";
echo "   Grupos: " . count($grouped) . "\n";
echo "   Endpoints: {$total}\n";
