<?php

declare(strict_types=1);

$distIndex = __DIR__ . '/dist/index.html';

if (!is_file($distIndex)) {
    http_response_code(503);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Frontend non compile. Lancez: npm run build\n";
    exit;
}

$html = file_get_contents($distIndex);
if (!is_string($html)) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Impossible de lire dist/index.html\n";
    exit;
}

$scriptPath = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? '/'));
$scriptDir = str_replace('\\', '/', dirname($scriptPath));
$publicBasePath = trim($scriptDir, '/');
$publicBasePath = $publicBasePath !== '' ? '/' . $publicBasePath : '';
$assetBasePath = ($publicBasePath !== '' ? $publicBasePath : '') . '/dist/';

$replacements = [
    '"/camparts/dist/' => '"' . $assetBasePath,
    "'/camparts/dist/" => "'" . $assetBasePath,
    '"/dist/' => '"' . $assetBasePath,
    "'/dist/" => "'" . $assetBasePath,
];
$html = str_replace(array_keys($replacements), array_values($replacements), $html);

$runtimeBasePath = $publicBasePath !== '' ? $publicBasePath : '/';
$bootstrapScript = '<script>window.__CAMPARTS_BASE_PATH__='
    . json_encode($runtimeBasePath, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
    . ';</script>';

$headPosition = stripos($html, '</head>');
if ($headPosition !== false) {
    $html = substr_replace($html, $bootstrapScript . "\n", $headPosition, 0);
} else {
    $html = $bootstrapScript . "\n" . $html;
}

header('Content-Type: text/html; charset=utf-8');
echo $html;
