#!/usr/bin/env php
<?php
declare(strict_types=1);
if (PHP_SAPI !== 'cli') { http_response_code(404); exit; }
require_once dirname(__DIR__) . '/app/Core/Version.php';
$command = $argv[1] ?? 'help';
if ($command === 'key:generate') { echo bin2hex(random_bytes(32)) . PHP_EOL; exit; }
if ($command === 'help') {
    echo "AdNova standalone core " . AdNova\Core\Version::CURRENT . "\n\n";
    echo "key:generate       Print a random application key\ninstall            Migrate an empty database and create its owner\nmigrate            Apply unapplied database migrations\ncheck              Check configuration, database and installation\nwallet:check       Reconcile credit balances against ledger entries\nmail:work          Deliver up to 10 queued account emails\nmail:status        Show account email queue totals\ncron:run           Deliver account emails, clean expired data and return credits from unanswered surf pages\nsurf:maintain      Return credits from unanswered surf pages and prune old page records\nmaintenance:on     Show members a 'being updated' page (the owner can still sign in)\nmaintenance:off    Open the site again\nbackup:create      Write a database backup to storage/backups\nbackup:list        List backups\nbackup:restore F   Restore backup file F into an EMPTY database\nimport:inspect M   Check an LFMTE/LFMVM import mapping file M against the old database\nimport:lfm M       Import from LFMTE/LFMVM using mapping file M (add --dry-run first, --limit=N)\nmail:campaigns     Send a batch of member mailings and close mailings whose click window ended\n\n";
    echo "install prompts for owner name, email and password. For automation, use\ninstall --owner-json-stdin and provide name/email/password as JSON on stdin.\n";
    exit;
}
try {
    $config = require dirname(__DIR__) . '/bootstrap.php';
    foreach (['logs', 'sessions', 'mail'] as $directory) {
        if (!is_dir($config->root . '/storage/' . $directory) || !is_writable($config->root . '/storage/' . $directory)) throw new RuntimeException('Storage directory is not writable: ' . $directory);
    }
    if (!is_writable($config->root . '/storage')) throw new RuntimeException('The storage directory is not writable.');
    $db = AdNova\Core\Database::connect($config);
    switch ($command) {
        case 'install':
            if (in_array('--owner-json-stdin', $argv, true)) {
                $raw = stream_get_contents(STDIN, 4097);
                if (strlen($raw) > 4096) throw new RuntimeException('Owner input is too large.');
                $owner = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
                if (!is_array($owner)) throw new RuntimeException('Owner input must be a JSON object.');
                foreach (['name', 'email', 'password'] as $field) if (!isset($owner[$field]) || !is_string($owner[$field])) throw new RuntimeException('Missing owner details.');
            } else {
                if (!stream_isatty(STDIN)) throw new RuntimeException('Use --owner-json-stdin for non-interactive setup.');
                $prompt = static function (string $label): string { fwrite(STDOUT, $label); return rtrim((string) fgets(STDIN), "\r\n"); };
                $owner = ['name' => $prompt('Owner name: '), 'email' => $prompt('Owner email: ')];
                if (!function_exists('exec')) throw new RuntimeException('Hidden terminal input unavailable. Use --owner-json-stdin.');
                exec('stty -echo', $output, $status);
                if ($status !== 0) throw new RuntimeException('Cannot hide terminal input. Use --owner-json-stdin.');
                try {
                    $owner['password'] = $prompt('Owner password (hidden): ');
                    fwrite(STDOUT, "\n");
                    $confirmation = $prompt('Repeat password (hidden): ');
                    fwrite(STDOUT, "\n");
                } finally { exec('stty echo'); }
                if (!hash_equals($owner['password'], $confirmation)) throw new RuntimeException('Passwords do not match.');
            }
            (new AdNova\Core\Installer($db, $config))->install($owner['name'], $owner['email'], $owner['password']);
            unset($owner);
            echo "Installation completed. Owner login: " . $config->url('/login') . "\n";
            break;
        case 'migrate':
            foreach ((new AdNova\Core\Migrator($db, $config))->run() as $version) echo 'Applied ' . $version . "\n";
            echo "Migrations are current.\n";
            break;
        case 'check':
            $installed = $db->query('SELECT version,installed_at FROM adnova_installation WHERE id=1')->fetch();
            if (!$installed) throw new RuntimeException('Installation is incomplete.');
            echo 'PHP ' . PHP_VERSION . '; database ' . $db->getAttribute(PDO::ATTR_SERVER_VERSION) . "\n";
            echo 'Application ' . AdNova\Core\Version::CURRENT . '; initially installed ' . $installed['version'] . ' at ' . $installed['installed_at'] . " UTC\n";
            echo 'Registration: ' . ($config->registrationOpen() ? 'enabled; verification required' : 'closed') . "\n";
            break;
        case 'wallet:check':
            $differences=(new AdNova\Platform\WalletService($db))->discrepancies();
            if($differences){echo json_encode($differences,JSON_THROW_ON_ERROR)."\n";throw new RuntimeException('Credit balances do not reconcile. Investigate before making further adjustments.');}
            echo "All credit balances reconcile to their ledger entries.\n";
            break;
        case 'maintenance:on': AdNova\Core\Maintenance::enable($config); echo "Maintenance mode is on.\n"; break;
        case 'maintenance:off': AdNova\Core\Maintenance::disable($config); echo "Maintenance mode is off.\n"; break;
        case 'backup:create':
            $b = (new AdNova\Core\BackupService($db, $config))->create();
            echo 'Backup written: storage/backups/' . $b['name'] . ' (' . $b['rows'] . " rows)\n";
            break;
        case 'backup:list':
            foreach ((new AdNova\Core\BackupService($db, $config))->all() as $b) echo $b['name'] . '  ' . $b['created'] . ' UTC  ' . $b['size'] . " bytes\n";
            break;
        case 'backup:restore':
            $file = $argv[2] ?? '';
            if (!is_file($file)) throw new RuntimeException('Give the backup file path: php bin/console backup:restore FILE');
            echo 'Restored ' . (new AdNova\Core\BackupService($db, $config))->restore($file) . " rows. Run wallet:check, then sign in.\n";
            break;
        case 'import:inspect':
        case 'import:lfm':
            $file = $argv[2] ?? '';
            if (!is_file($file)) throw new RuntimeException('Give the mapping file path, for example storage/import/lfm.json (see docs/IMPORT-LFM.md).');
            $map = AdNova\Import\LfmImporter::mapping(json_decode((string) file_get_contents($file), true, 64, JSON_THROW_ON_ERROR));
            $importer = new AdNova\Import\LfmImporter($db, $config, AdNova\Import\LfmImporter::connect($map['source']), $map);
            if ($command === 'import:inspect') { echo json_encode($importer->inspect(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"; break; }
            $limit = null;
            foreach ($argv as $arg) if (preg_match('/^--limit=([1-9][0-9]{0,8})$/', $arg, $mm)) $limit = (int) $mm[1];
            echo json_encode($importer->run(in_array('--dry-run', $argv, true), $limit), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n";
            break;
        case 'mail:campaigns':
            echo json_encode((new AdNova\Mailer\CampaignWorker($db, $config))->run(), JSON_THROW_ON_ERROR) . "\n";
            break;
        case 'surf:maintain':
            echo json_encode((new AdNova\Traffic\SurfService($db))->maintain(), JSON_THROW_ON_ERROR) . "\n";
            break;
        case 'mail:status':
            foreach ($db->query('SELECT status,COUNT(*) AS total FROM adnova_account_mail GROUP BY status') as $row) echo $row['status'] . ': ' . $row['total'] . "\n";
            break;
        case 'mail:work':
            echo json_encode((new AdNova\Mail\AccountMailWorker($db,$config))->run(), JSON_THROW_ON_ERROR) . "\n";
            break;
        case 'cron:run':
            $query = $db->prepare('DELETE FROM adnova_rate_limits WHERE expires_at < ? LIMIT 1000');
            $query->execute([time()]);
            echo 'Removed ' . $query->rowCount() . " expired authentication buckets.\n";
            $db->prepare('DELETE FROM adnova_account_tokens WHERE expires_at<?')->execute([time()]);
            // Some hosts disable PHP session garbage collection for custom save paths.
            // Sessions end after 12 hours at most, so older files are always unusable.
            $removed = 0;
            foreach (glob($config->root . '/storage/sessions/sess_*') ?: [] as $file) {
                if (is_file($file) && filemtime($file) < time() - 43200 && @unlink($file)) $removed++;
            }
            echo 'Removed ' . $removed . " expired session files.\n";
            echo 'Traffic exchange: ' . json_encode((new AdNova\Traffic\SurfService($db))->maintain(), JSON_THROW_ON_ERROR) . "\n";
            echo 'Member mailings: ' . json_encode((new AdNova\Mailer\CampaignWorker($db, $config))->run(), JSON_THROW_ON_ERROR) . "\n";
            $db->exec("UPDATE adnova_account_mail m LEFT JOIN adnova_account_tokens t ON t.token_hash=m.token_hash SET m.status='cancelled',m.payload=NULL WHERE t.token_hash IS NULL AND m.status IN ('pending','failed')");
            if ($config->mailEnabled()) echo json_encode((new AdNova\Mail\AccountMailWorker($db,$config))->run(), JSON_THROW_ON_ERROR) . "\n";
            else echo "Account email is disabled.\n";
            break;
        default:
            throw new RuntimeException('Unknown command. Run php bin/console help.');
    }
} catch (Throwable $error) {
    // CLI setup output is local to the operator, never a web response.
    fwrite(STDERR, 'Error: ' . $error->getMessage() . "\n");
    exit(1);
}
