<?php
declare(strict_types=1);

/**
 * Final deploy readiness check for Step 7.
 *
 * Run after .env and .cpanel.yml are configured:
 *   php scripts/deploy_ready.php staging
 *   php scripts/deploy_ready.php production
 */

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo "403 Forbidden\n";
    exit(1);
}

$root = dirname(__DIR__);
$expectedEnv = $argv[1] ?? '';
$failed = false;

if (!in_array($expectedEnv, ['staging', 'production'], true)) {
    fwrite(STDERR, "Usage: php scripts/deploy_ready.php <staging|production>\n");
    exit(1);
}

function read_env_file(string $path): array
{
    $values = [];
    if (!is_file($path)) {
        return $values;
    }

    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines ?: [] as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
            continue;
        }
        [$key, $value] = explode('=', $line, 2);
        $values[trim($key)] = trim($value);
    }

    return $values;
}

function check_item(bool $ok, string $message, string $detail = ''): void
{
    global $failed;
    echo '[' . ($ok ? 'OK' : 'FAIL') . '] ' . $message;
    if ($detail !== '') {
        echo ' - ' . $detail;
    }
    echo PHP_EOL;

    if (!$ok) {
        $failed = true;
    }
}

$envPath = $root . '/.env';
$cpanelPath = $root . '/.cpanel.yml';
$env = read_env_file($envPath);
$cpanel = is_file($cpanelPath) ? (string) file_get_contents($cpanelPath) : '';

check_item(is_file($envPath), '.env exists');
check_item(($env['APP_ENV'] ?? '') === $expectedEnv, "APP_ENV is {$expectedEnv}", $env['APP_ENV'] ?? 'missing');
check_item(!empty($env['APP_URL'] ?? ''), 'APP_URL configured', $env['APP_URL'] ?? '');
check_item(!empty($env['DB_NAME'] ?? '') && !str_starts_with(($env['DB_NAME'] ?? ''), 'ISI_'), 'DB_NAME configured');
check_item(!empty($env['DB_USER'] ?? '') && !str_starts_with(($env['DB_USER'] ?? ''), 'ISI_'), 'DB_USER configured');
check_item(!empty($env['DB_PASS'] ?? '') && !str_starts_with(($env['DB_PASS'] ?? ''), 'ISI_'), 'DB_PASS configured');
check_item(!empty($env['HEALTHCHECK_TOKEN'] ?? '') && !str_starts_with(($env['HEALTHCHECK_TOKEN'] ?? ''), 'GANTI_'), 'HEALTHCHECK_TOKEN configured');

check_item(is_file($cpanelPath), '.cpanel.yml exists');
check_item($cpanel !== '' && !str_contains($cpanel, '/home/USERNAME/'), '.cpanel.yml username replaced');
check_item($cpanel !== '' && str_contains($cpanel, 'rsync -av --delete'), '.cpanel.yml uses rsync deploy');
check_item($cpanel !== '' && str_contains($cpanel, "--exclude='.env'"), '.cpanel.yml excludes .env');
check_item($cpanel !== '' && str_contains($cpanel, "--exclude='uploads/*'"), '.cpanel.yml excludes uploads');
check_item($cpanel !== '' && str_contains($cpanel, "--exclude='storage/backups/*'"), '.cpanel.yml excludes backups');

$requiredScripts = [
    'scripts/post_deploy.php',
    'scripts/preflight.php',
    'scripts/healthcheck.php',
    'scripts/migrate.php',
    'scripts/backup_files.php',
    'scripts/backup_database.php',
    'scripts/release_check.php',
];

foreach ($requiredScripts as $relativePath) {
    check_item(is_file($root . '/' . $relativePath), "{$relativePath} exists");
}

$runtimeDirs = [
    'storage/logs',
    'storage/cache',
    'storage/exports',
    'storage/backups',
    'uploads',
    'exports',
];

foreach ($runtimeDirs as $relativePath) {
    $path = $root . '/' . $relativePath;
    check_item(is_dir($path), "{$relativePath} exists");
    check_item(is_dir($path) && is_writable($path), "{$relativePath} writable");
}

if ($failed) {
    echo PHP_EOL . "Deploy readiness FAILED. Fix every FAIL item before deploying {$expectedEnv}.\n";
    exit(1);
}

echo PHP_EOL . "Deploy readiness PASS for {$expectedEnv}.\n";
