#!/usr/bin/env php
<?php
declare(strict_types=1);
$root = dirname(__DIR__);
foreach (
    ['DB', 'Migrations', 'BackupService', 'AppSettings', 'Asm3Analyzer', 'Asm3ContactPlanner', 'Asm3ContactImporter']
    as $service
) {
    require $root . '/app/Services/' . $service . '.php';
}
$source = null;
$apply = false;
foreach (array_slice($argv, 1) as $arg) {
    if ($arg === '--apply') {
        $apply = true;
    } elseif (str_starts_with($arg, '--')) {
        fwrite(STDERR, "Option inconnue : {$arg}\n");
        exit(2);
    } else {
        $source = $arg;
    }
}
if (!$source) {
    fwrite(STDERR, "Usage : php scripts/asm3-contacts.php <dump.sql> [--apply]\n");
    exit(2);
}
if ($apply) {
    fwrite(STDERR, 'IMPORT CONTACTS demandé. Tapez IMPORTER CONTACTS : ');
    if (trim((string) fgets(STDIN)) !== 'IMPORTER CONTACTS') {
        fwrite(STDERR, "Import annulé.\n");
        exit(3);
    }
}
try {
    Migrations::run($root . '/migrations');
    echo json_encode(Asm3ContactImporter::run($source, DB::pdo(), $apply), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE),
        "\n";
} catch (Throwable $e) {
    fwrite(STDERR, "Échec : {$e->getMessage()}\n");
    exit(1);
}
