#!/usr/bin/env php
<?php
declare(strict_types=1);
$root = dirname(__DIR__);
require $root . '/app/Services/DB.php';
require $root . '/app/Services/Migrations.php';
require $root . '/app/Services/BackupService.php';
require $root . '/app/Services/AppSettings.php';
require $root . '/app/Services/Asm3Analyzer.php';
require $root . '/app/Services/Asm3MigrationPlanner.php';
require $root . '/app/Services/Asm3AnimalImporter.php';
$source = null;
$apply = false;
foreach (array_slice($argv, 1) as $arg) {
    if ($arg === '--apply') {
        $apply = true;
        continue;
    }
    if (str_starts_with($arg, '--')) {
        fwrite(STDERR, "Option inconnue : {$arg}\n");
        exit(2);
    }
    $source = $arg;
}
if (!$source) {
    fwrite(
        STDERR,
        "Usage : php scripts/asm3-import.php <dump.sql> [--apply]\nSans --apply, aucune donnée métier n’est écrite.\n",
    );
    exit(2);
}
if ($apply) {
    fwrite(STDERR, 'IMPORT RÉEL demandé. Tapez exactement IMPORTER ASM3 pour continuer : ');
    if (trim((string) fgets(STDIN)) !== 'IMPORTER ASM3') {
        fwrite(STDERR, "Import annulé.\n");
        exit(3);
    }
}
try {
    Migrations::run($root . '/migrations');
    $result = Asm3AnimalImporter::run($source, DB::pdo(), $apply);
    echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
} catch (Throwable $e) {
    fwrite(STDERR, "Échec : {$e->getMessage()}\n");
    exit(1);
}
