<?php
/**
 * CLI: empty operational data, keep table structures + users + settings.
 *
 * Usage (from project root):
 *   php install/prepare-live-database.php
 *   php install/prepare-live-database.php --dry-run
 */

if (php_sapi_name() !== 'cli') {
    fwrite(STDERR, "Run from command line only.\n");
    exit(1);
}

$dryRun = in_array('--dry-run', $argv ?? [], true);

require_once __DIR__ . '/../config/app.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/db-clean-data.php';
require_once __DIR__ . '/../includes/db-table-stats.php';

$preserve = nazareth_db_clean_preserve_tables();
$tables = nazarethListBaseTablesWithStats($pdo);
$toTruncate = [];
$preserved = [];

foreach ($tables as $t) {
    if (in_array(strtolower($t['name']), array_map('strtolower', $preserve), true)) {
        $preserved[] = $t['name'] . ' (' . number_format($t['rows']) . ' rows kept)';
    } else {
        $toTruncate[] = $t['name'] . ' (' . number_format($t['rows']) . ' rows)';
    }
}

echo "Database: " . ($pdo->query('SELECT DATABASE()')->fetchColumn() ?: '?') . "\n";
echo "Preserve: " . implode(', ', $preserve) . "\n\n";

if ($preserved) {
    echo "Kept:\n";
    foreach ($preserved as $line) {
        echo "  - $line\n";
    }
    echo "\n";
}

echo "Will truncate (" . count($toTruncate) . " tables):\n";
foreach ($toTruncate as $line) {
    echo "  - $line\n";
}

if ($dryRun) {
    echo "\nDry run only — no changes made.\n";
    exit(0);
}

echo "\nTruncating in 3 seconds… (Ctrl+C to cancel)\n";
sleep(3);

$result = nazareth_clean_database_data($pdo, $preserve);

echo "\nDone.\n";
echo 'Truncated: ' . count($result['truncated']) . " table(s)\n";
if ($result['skipped']) {
    echo "Skipped:\n";
    foreach ($result['skipped'] as $s) {
        echo "  - $s\n";
    }
}

exit(empty($result['skipped']) ? 0 : 1);
