<?php
/**
 * @intranet-file tools/generate_version_manifest.php
 * @intranet-file-version 2026.03.13.1
 * @intranet-file-date 2026-03-13
 * @intranet-file-owner CSIF Intranet
 */
declare(strict_types=1);

$root = dirname(__DIR__);
$versionFile = $root . '/config/version.php';
$manifestFile = $root . '/config/version_manifest.json';

$versionMeta = require $versionFile;
$version = (string)($versionMeta['version'] ?? '0.0.0.0');
$buildDate = (string)($versionMeta['build_date'] ?? date('Y-m-d'));

$skipPrefixes = [
    'vendor/',
    'common/vendor/',
    'docs/',
    'styles/images/',
    'output/',
    'tmp/',
];
$skipExact = [
    'common/Inkfree.ttf',
];
$allowedExts = ['php','js','css','sql','md','html','json','txt'];

$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS));
$files = [];

foreach ($rii as $file) {
    if (!$file->isFile()) {
        continue;
    }

    $absPath = $file->getPathname();
    $relPath = str_replace('\\', '/', substr($absPath, strlen($root) + 1));

    if (in_array($relPath, $skipExact, true)) {
        continue;
    }

    $skip = false;
    foreach ($skipPrefixes as $prefix) {
        if (str_starts_with($relPath, $prefix)) {
            $skip = true;
            break;
        }
    }
    if ($skip) {
        continue;
    }

    $ext = strtolower(pathinfo($relPath, PATHINFO_EXTENSION));
    if ($relPath !== '.htaccess' && !in_array($ext, $allowedExts, true) && basename($relPath) !== '.htaccess') {
        continue;
    }

    $hash = hash_file('sha256', $absPath);
    $files[] = [
        'path' => $relPath,
        'sha256' => $hash,
        'bytes' => filesize($absPath),
        'version' => $version,
        'build_date' => $buildDate,
    ];
}

usort($files, static fn(array $a, array $b): int => strcmp($a['path'], $b['path']));

$payload = [
    'intranet_version' => $version,
    'build_date' => $buildDate,
    'generated_at' => date('c'),
    'notes' => 'Manifest de control de versiones y huellas SHA-256 de ficheros fuente propios.',
    'files' => $files,
];

file_put_contents($manifestFile, json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
echo "Manifest generado en {$manifestFile}\n";
