<?php
/**
 * Generador de Índice Comprimido para unmscrm.apib (API Blueprint UCRM)
 * 
 * USO: php gen_index_ucrm_apib.php
 * SALIDA: INDEX_api_ucrm.md en la raíz del plugin
 * 
 * Reduce ~266KB (65K tokens) → ~10KB (2-3K tokens)
 */

$apibPath   = __DIR__ . '/../references/unmscrm.apib';
$outputPath = __DIR__ . '/../../INDEX_api_ucrm.md';

if (!file_exists($apibPath)) {
    die("ERROR: No se encontró unmscrm.apib en: $apibPath\n");
}

echo "Leyendo unmscrm.apib (" . round(filesize($apibPath) / 1024, 1) . " KB)...\n";

$content = file_get_contents($apibPath);
$lines   = explode("\n", $content);

$groups  = [];
$current_group = 'General';
$current_resource = '';

foreach ($lines as $line) {
    $line = rtrim($line);

    // Grupo: "# Group Clients"
    if (preg_match('/^#\s+Group\s+(.+)$/i', $line, $m)) {
        $current_group = trim($m[1]);
        if (!isset($groups[$current_group])) {
            $groups[$current_group] = [];
        }
        continue;
    }

    // Recurso nivel 1: "# /clients{?param1,param2}" — solo si empieza con /
    if (preg_match('/^#\s+(\/[^\s{]+)/', $line, $m)) {
        // Limpiar parámetros de query string del path
        $raw_path = $m[1];
        $current_resource = preg_replace('/\{[^}]*\}/', '', $raw_path); // quitar {?params}
        continue;
    }

    // Recurso nivel 2 con path en brackets: "## Client [/clients/{id}]"
    if (preg_match('/^##\s+[^[]+\[([^\]]+)\]/', $line, $m)) {
        $current_resource = trim($m[1]);
        continue;
    }

    // Recurso nivel 2 que es un path: "## /clients/{id}"
    if (preg_match('/^##\s+(\/[^\s{]+)/', $line, $m)) {
        $current_resource = $m[1];
        continue;
    }

    // Método HTTP nivel 2 directo: "## GET" or "## POST"
    if (preg_match('/^##\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s*$/i', $line, $m)) {
        $method = strtoupper($m[1]);
        if (!isset($groups[$current_group])) {
            $groups[$current_group] = [];
        }
        $groups[$current_group][] = [
            'method' => $method,
            'path'   => $current_resource ?: '/',
            'desc'   => '—',
        ];
        continue;
    }

    // Método HTTP nivel 3: "### Descripción [METHOD /path]"
    if (preg_match('/^###\s+(.+)$/i', $line, $m)) {
        $raw  = trim($m[1]);
        $method = '';
        $path   = $current_resource;
        $desc   = $raw;

        // Formato: "Create Client [POST /clients]"
        if (preg_match('/\[(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s*([^\]]*)\]/i', $raw, $pm)) {
            $method = strtoupper($pm[1]);
            $pathInBracket = trim($pm[2]);
            if ($pathInBracket) $path = $pathInBracket;
            $desc = trim(preg_replace('/\[.+\]/', '', $raw));
        }
        // Formato: "GET /path Description"
        elseif (preg_match('/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+(\S+)\s*(.*)$/i', $raw, $pm)) {
            $method = strtoupper($pm[1]);
            $path   = $pm[2];
            $desc   = trim($pm[3]) ?: '—';
        }
        // Formato: Solo METHOD
        elseif (preg_match('/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)$/i', $raw, $pm)) {
            $method = strtoupper($pm[1]);
            $desc   = '—';
        }

        if ($method) {
            if (!isset($groups[$current_group])) {
                $groups[$current_group] = [];
            }
            $groups[$current_group][] = [
                'method' => $method,
                'path'   => $path ?: '/',
                'desc'   => $desc ?: '—',
            ];
        }
        continue;
    }
}

// Generar Markdown
$output_lines = [];
$output_lines[] = "# Índice API UCRM — CRM v1.0";
$output_lines[] = "";
$output_lines[] = "> **Generado automáticamente** desde `unmscrm.apib`";
$output_lines[] = "> Ejecutar `php .agent/scripts/gen_index_ucrm_apib.php` para regenerar.";
$output_lines[] = "";
$output_lines[] = "**Base URL:** `https://{ipserver}/crm/api/v1.0/`";
$output_lines[] = "**Auth:** Header `X-Auth-App-Key: {apitoken}`";
$output_lines[] = "";
$output_lines[] = "---";
$output_lines[] = "";
$output_lines[] = "## Resumen de Grupos";
$output_lines[] = "";

$total = 0;
foreach ($groups as $group => $ops) {
    $count = count($ops);
    $total += $count;
    $output_lines[] = "- **{$group}** ({$count} endpoints)";
}
$output_lines[] = "";
$output_lines[] = "**Total: {$total} endpoints en " . count($groups) . " grupos**";
$output_lines[] = "";
$output_lines[] = "---";
$output_lines[] = "";

foreach ($groups as $group => $ops) {
    if (empty($ops)) continue;
    $output_lines[] = "## {$group}";
    $output_lines[] = "";
    foreach ($ops as $op) {
        $output_lines[] = sprintf(
            "  - %-8s `%s` — %s",
            $op['method'],
            $op['path'],
            $op['desc']
        );
    }
    $output_lines[] = "";
}

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

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

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