<?php
declare(strict_types=1);

$__hostRedirects = [
    'i.endure.digital'   => '/en/authors/fernando-caicedo/',
    'me.endure.digital'  => '/en/authors/fernando-caicedo/',
    'soy.endure.digital' => '/es/autores/fernando-caicedo/',
    'yo.endure.digital'  => '/es/autores/fernando-caicedo/',
];
$__reqHost = $_SERVER['HTTP_HOST'] ?? '';
if (isset($__hostRedirects[$__reqHost])) {
    header('Location: ' . $__hostRedirects[$__reqHost], true, 301);
    exit;
}

if (php_sapi_name() === 'cli-server') {
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    if ($path !== '/' && is_file(__DIR__ . $path)) {
        return false; // serve static file
    }
}

if (!defined('PROJECT'))   define('PROJECT',   realpath(__DIR__ . '/..'));
if (!defined('CONTENT'))   define('CONTENT',   PROJECT . '/content');
if (!defined('CONFIG'))    define('CONFIG',    PROJECT . '/config');
if (!defined('GENERATED')) define('GENERATED', PROJECT . '/public/generated');

// D237: no-store en dev para evitar HTML stale en el navegador
if (getenv('EIK_ENV') !== 'prod' && PHP_SAPI !== 'cli') {
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Expires: 0');
}


/** D197: mtime más reciente de lib/*.php (invalidación por código) */
function latestLibMtime(): int {
    static $cached = null;
    if ($cached !== null) return $cached;
    $max = 0;
    foreach (glob(PROJECT . '/lib/*.php') ?: [] as $f) {
        $m = @filemtime($f);
        if ($m !== false && $m > $max) $max = $m;
    }
    foreach (glob(PROJECT . '/templates/_themes/endure/*.php') ?: [] as $f) {
        $m = @filemtime($f);
        if ($m !== false && $m > $max) $max = $m;
    }
    return $cached = $max;
    // D254: entity/authors JSON invalidan HTML cache
    foreach (glob(PROJECT . '/data/entities/*.json') ?: [] as $__f) $files[] = $__f;
    foreach (glob(PROJECT . '/data/authors/*/*.json') ?: [] as $__f) $files[] = $__f;
}


require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../lib/parser.php';
require_once __DIR__ . '/../lib/walk.php';
require_once __DIR__ . '/../lib/paths.php';
require_once __DIR__ . '/../lib/links.php';
require_once __DIR__ . '/../lib/citations.php';
require_once __DIR__ . '/../lib/embed.php';
require_once __DIR__ . '/../lib/taxonomy.php';
require_once __DIR__ . '/../lib/render.php';
require_once __DIR__ . '/../lib/seo.php';
require_once __DIR__ . '/../lib/menu.php';
require_once __DIR__ . '/../lib/page-renderer.php';

use Symfony\Component\Yaml\Yaml;

$host = strtolower($_SERVER['HTTP_HOST'] ?? 'localhost');
$host = preg_replace('/:\d+$/', '', $host);
$uri  = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$uri  = '/' . trim($uri, '/') . '/';
$slug = trim($uri, '/');

$sites = Yaml::parseFile(CONFIG . '/sites.yaml');
$siteName = null;
if (isset($sites['sites'][$host])) {
    $siteName = $host;
} elseif (isset($sites['aliases'][$host], $sites['sites'][$sites['aliases'][$host]])) {
    $siteName = $sites['aliases'][$host];
}
if ($siteName === null) {
    http_response_code(404);
    exit('Host no configurado: ' . htmlspecialchars($host));
}
$site = $sites['sites'][$siteName];

// ---- Ruta de taxonomía ----
if ($slug === 'temas' || str_starts_with($slug, 'temas/')) {
    $taxPage = buildTaxonomyPage($siteName, $site, $slug);
    if ($taxPage !== null) {
        header('Content-Type: text/html; charset=utf-8');
        header('X-Cache: DYNAMIC');
        echo renderPageToHtml($taxPage, null, $site, $host, $siteName);
        exit;
    }
}

// D248: Ocultar idiomas inactivos en producción
$reqLang = explode('/', trim($uri, '/'))[0] ?? '';
$activeLangs = $site['active_languages'] ?? ['en', 'es'];
if (getenv('EIK_ENV') === 'prod' && in_array($reqLang, ['it', 'pt'], true) && !in_array($reqLang, $activeLangs, true)) {
    http_response_code(404);
    // Opcional: render404($site, $host, $uri);
    echo '<h1>404 Not Found</h1><p>This language is not yet available in production.</p>';
    exit;
}

// ---- Página normal ----
$result = findPage($siteName, $slug);
if ($result === null) {
    http_response_code(404);
    render404($site, $host, $uri);
    exit;
}

$sourceFile = $result['page']['_file'] ?? null;
$cacheFile  = GENERATED . '/' . $host . $uri . 'index.html';
$libMtime = latestLibMtime();
    $useCache = !isset($_GET['nocache']) && is_file($cacheFile)
             && $sourceFile
             && filemtime($cacheFile) >= filemtime($sourceFile)
             && filemtime($cacheFile) >= $libMtime;

if ($useCache) {
    header('Content-Type: text/html; charset=utf-8');
    header('X-Cache: HIT');
    readfile($cacheFile);
    exit;
}

header('Content-Type: text/html; charset=utf-8');
header('X-Cache: MISS');

$html = renderPageToHtml($result['page'], $result['virtual'], $site, $host, $siteName);

if ($sourceFile) {
    $dir = dirname($cacheFile);
    if (!is_dir($dir)) @mkdir($dir, 0755, true);
    @file_put_contents($cacheFile, $html);
}

echo $html;

// ============================================================
function buildTaxonomyPage(string $siteName, array $site, string $slug): ?array
{
    $lang = $site['default_lang'] ?? 'es';
    $parts = explode('/', $slug);
    $dim   = $parts[1] ?? null;
    $value = $parts[2] ?? null;

    if ($dim === null) {
        $html = '<div class="taxonomy-list-wrap">';
        foreach (taxonomyDims() as $d) {
            $vals = taxonomyValues($d);
            if (empty($vals)) continue;
            $html .= '<h3>' . htmlspecialchars($d) . '</h3><ul class="taxonomy-list" data-dim="' . htmlspecialchars($d) . '">';
            foreach ($vals as $v) {
                $safe = preg_replace('/[^a-z0-9\-_]/i', '-', (string)$v['value']);
                $html .= '<li><a href="/temas/' . htmlspecialchars($d) . '/' . htmlspecialchars($safe) . '/">'
                       . htmlspecialchars((string)$v['value']) . '</a> <span class="count">(' . (int)$v['count'] . ')</span></li>';
            }
            $html .= '</ul>';
        }
        $html .= '</div>';
        return [
            'id' => ['slug' => 'temas', 'site' => $siteName, 'path' => '/temas/'],
            'type' => ['kind' => 'taxonomy'],
            'language' => ['primary' => $lang],
            'presentation' => [
                'title' => 'Temas · Índice de taxonomías',
                'summary' => 'Todas las dimensiones de clasificación del jardín: vertical, topic, audience, intent, region.',
            ],
            '_tax' => ['level' => 'index', 'html' => $html],
        ];
    }

    if ($value === null) {
        $vals = taxonomyValues($dim);
        if (empty($vals)) return null;
        $html = '<ul class="taxonomy-list" data-dim="' . htmlspecialchars($dim) . '">';
        foreach ($vals as $v) {
            $safe = preg_replace('/[^a-z0-9\-_]/i', '-', (string)$v['value']);
            $html .= '<li><a href="/temas/' . htmlspecialchars($dim) . '/' . htmlspecialchars($safe) . '/">'
                   . htmlspecialchars((string)$v['value']) . '</a> <span class="count">(' . (int)$v['count'] . ')</span></li>';
        }
        $html .= '</ul>';
        return [
            'id' => ['slug' => 'temas-' . $dim, 'site' => $siteName, 'path' => '/temas/' . $dim . '/'],
            'type' => ['kind' => 'taxonomy'],
            'language' => ['primary' => $lang],
            'presentation' => [
                'title' => 'Temas · ' . ucfirst($dim),
                'summary' => 'Todos los valores de la dimensión "' . $dim . '".',
            ],
            '_tax' => ['level' => 'dim', 'dim' => $dim, 'html' => $html],
        ];
    }

    $pages = taxonomyPages($dim, $value);
    if (empty($pages)) return null;
    $html = '<ul class="page-list">';
    foreach ($pages as $p) {
        $html .= '<li><a href="' . htmlspecialchars($p['path']) . '">'
               . htmlspecialchars($p['title'] ?: $p['slug']) . '</a>'
               . ' <span class="kind">[' . htmlspecialchars($p['kind'] ?? '') . ']</span></li>';
    }
    $html .= '</ul>';
    return [
        'id' => ['slug' => 'temas-' . $dim . '-' . $value, 'site' => $siteName, 'path' => '/temas/' . $dim . '/' . rawurlencode($value) . '/'],
        'type' => ['kind' => 'taxonomy'],
        'language' => ['primary' => $lang],
        'presentation' => [
            'title' => ucfirst($value) . ' · ' . ucfirst($dim),
            'summary' => 'Páginas clasificadas con ' . $dim . '=' . $value . '.',
        ],
        '_tax' => ['level' => 'value', 'dim' => $dim, 'value' => $value, 'html' => $html],
    ];
}

function buildUrlMap(): array
{
    static $map = null;
    if ($map !== null) return $map;
    $map = [];
    foreach (walkContent() as $file) {
        $front = loadContentYaml($file);
        if ($front === null) continue;
        $urlPath = $front['id']['path'] ?? null;
        $sName   = $front['id']['site'] ?? null;
        if (!$urlPath || !$sName) continue;
        $key = $sName . '|' . normalizePath($urlPath);
        if (isset($map[$key]) && $map[$key] !== $file->getPathname()) {
            // D165: no fatal — preferir folder form (article.yaml) sobre flat, continuar.
        $existing  = $map[$key];
        $candidate = $file->getPathname();
        $isFolder  = static function ($x) { return strpos((string)$x, "/article.yaml") !== false; };
        $keep      = ($isFolder($candidate) && !$isFolder($existing)) ? $candidate : $existing;
        error_log("WARN url collision: {$key} — keeping {$keep}");
        $map[$key] = $keep;
        continue;
        }
        $map[$key] = $file->getPathname();
    }
    return $map;
}

function normalizePath(string $p): string
{
    $t = trim($p, '/');
    return $t === '' ? '/' : '/' . $t . '/';
}

function findPage(string $siteName, string $slug): ?array
{
    $map = buildUrlMap();
    if ($slug === '') {
        $key = $siteName . '|/';
        return isset($map[$key]) ? ['page' => loadPage($map[$key]), 'virtual' => null] : null;
    }
    $key = $siteName . '|' . normalizePath($slug);
    if (isset($map[$key])) return ['page' => loadPage($map[$key]), 'virtual' => null];

    $parts = explode('/', $slug);
    if (count($parts) < 2) return null;
    $vSlug = array_pop($parts);
    $pKey  = $siteName . '|' . normalizePath(implode('/', $parts));
    if (!isset($map[$pKey])) return null;
    $parent = loadPage($map[$pKey]);
    $virtuals = parseVirtualPages($parent['_body'] ?? '');
    if (!isset($virtuals[$vSlug])) return null;
    return ['page' => $parent, 'virtual' => $virtuals[$vSlug]];
}

function loadPage(string $file): array
{
    $raw = file_get_contents($file);
    if (preg_match('/^---\r?\n(.*?)\r?\n---\r?\n(.*)$/s', $raw, $m)) {
        try { $front = Yaml::parse($m[1]) ?? []; }
        catch (Throwable $e) { $front = []; error_log('[eik] ' . $e->getMessage()); }
        $body = $m[2];
    } else { $front = []; $body = $raw; }
    $front['_body'] = $body;
    $front['_file'] = $file;
    $front = hydrateFrontmatterV2($front, $file);
    return $front;
}

function render404(array $site, string $host, string $uri): void
{
    http_response_code(404);
    echo '<!doctype html><html lang="es"><head><meta charset="utf-8"><title>404</title>';
    echo '<link rel="stylesheet" href="/assets/css/main.css"></head><body>';
    echo '<main style="max-width:60ch;margin:4rem auto;padding:2rem;">';
    echo '<h1>404 · Página no encontrada</h1>';
    echo '<p>La ruta <code>' . htmlspecialchars($uri) . '</code> no existe.</p>';
    echo '<p><a href="/">Volver al inicio</a></p>';
    echo '</main></body></html>';
}
