<?php
/**
 * Antara — bootstrap for any auth-aware entry point.
 * Order matters: paths -> crypto -> store -> session -> migrate(if needed).
 *
 * This file is safe to include multiple times.
 */

if (defined('ANTARA_AUTH_BOOTSTRAPPED')) return;
define('ANTARA_AUTH_BOOTSTRAPPED', true);

if (!defined('ANTARA_ROOT')) {
    define('ANTARA_ROOT', dirname(__DIR__, 2));
}

require_once __DIR__ . '/../security/paths.php';
require_once __DIR__ . '/../security/crypto.php';
require_once __DIR__ . '/../security/logger.php';
require_once __DIR__ . '/../security/sanitize.php';
require_once __DIR__ . '/../security/csrf.php';
require_once __DIR__ . '/../security/rate_limit.php';
require_once __DIR__ . '/store.php';
require_once __DIR__ . '/session.php';
require_once __DIR__ . '/webauthn.php';
require_once __DIR__ . '/migrate.php';

AntaraPaths::ensureDirs();

// One-shot migration: only runs if /data/users.json exists and users.enc is empty.
try {
    if (AntaraMigrator::needsMigration()) {
        AntaraMigrator::run();
    }
} catch (\Throwable $e) {
    AntaraLogger::log('bootstrap.migrate_failed', ['error' => $e->getMessage()]);
}

// Always start the session so CSRF tokens / user state are available.
AntaraSession::start();

// Send conservative security headers for any auth-rendered HTML.
if (PHP_SAPI !== 'cli' && !headers_sent()) {
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: SAMEORIGIN');
    // strict-origin-when-cross-origin: YouTube embeds fallan con Error 153 si es same-origin (sin Referer).
    header('Referrer-Policy: strict-origin-when-cross-origin');
    header('Permissions-Policy: publickey-credentials-get=(self), publickey-credentials-create=(self)');
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https');
    if ($https) {
        header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
    }
}
