<?php
declare(strict_types=1);

const CODE_DIR_NAME = 'code';

function send_page_headers(): void {
  header('Content-Type: text/html; charset=utf-8');
  header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
  header('Pragma: no-cache');
  header('Expires: 0');
  header('Surrogate-Control: no-store');
}

function script_base_path(): string {
  $dir = rtrim(str_replace('\\', '/', dirname((string)($_SERVER['SCRIPT_NAME'] ?? ''))), '/');
  return ($dir === '' || $dir === '.') ? '' : $dir;
}

function installer_url(): string {
  return script_base_path() . '/install.php';
}

function installation_ready(string $codeDir): bool {
  $requiredFiles = [
    $codeDir . '/index.html',
    $codeDir . '/api.php',
    $codeDir . '/.lib/app_version.php',
    $codeDir . '/.lib/db.php',
    $codeDir . '/.data/state.json',
  ];
  foreach ($requiredFiles as $file) {
    if (!is_file($file) || !is_readable($file)) return false;
  }

  $requiredDirs = [
    $codeDir . '/.data',
    $codeDir . '/.manager-saves',
    $codeDir . '/.manager-saves/.meta',
    $codeDir . '/.manager-save-backups',
    $codeDir . '/uploads/manager-chat',
    $codeDir . '/reports',
  ];
  foreach ($requiredDirs as $dir) {
    if (!is_dir($dir) || !is_readable($dir) || !is_writable($dir)) return false;
  }

  return is_writable($codeDir . '/.data/state.json');
}

function redirect_to_installer(): void {
  $target = installer_url();
  header('Location: ' . $target, true, 302);
  header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
  echo 'Redirecting to installer: ' . htmlspecialchars($target, ENT_QUOTES, 'UTF-8');
  exit;
}

function inject_app_bootstrap(string $html, string $apiBase, string $version): string {
  $head = '<head>' . "\n"
    . '  <base href="' . CODE_DIR_NAME . '/">' . "\n"
    . '  <script>window.YSP_API_BASE=' . json_encode($apiBase, JSON_UNESCAPED_SLASHES)
    . ';window.YSP_APP_VERSION=' . json_encode($version, JSON_UNESCAPED_SLASHES) . ';</script>';

  return preg_replace('/<head>/i', $head, $html, 1) ?? $html;
}

$codeDir = __DIR__ . '/' . CODE_DIR_NAME;

if (!installation_ready($codeDir)) redirect_to_installer();

require_once $codeDir . '/.lib/app_version.php';

$version = ysp_app_version($codeDir);
$html = file_get_contents($codeDir . '/index.html');
if ($html === false) {
  http_response_code(500);
  echo 'Could not load app';
  exit;
}

$apiBase = script_base_path() . '/' . CODE_DIR_NAME . '/api.php';
$html = inject_app_bootstrap($html, $apiBase, $version);

send_page_headers();
echo str_replace('__APP_VERSION__', (string)$version, $html);
