<?php
/**
 * CLI ingest runner — calls CollectionEngine directly.
 *
 *   php bin/ingest-cli.php facility-mapping <report_id> "/path/to/Mapping.csv"
 *   php bin/ingest-cli.php collection       <report_id> "/path/to/Collection Raw.csv"
 *
 *   <report_id> can be a numeric id from the reports table, or the report
 *   code (e.g. COLL-DASH) for convenience.
 */
if (php_sapi_name() !== 'cli') { http_response_code(403); exit('CLI only'); }

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/collection-engine.php';

$kind   = $argv[1] ?? '';
$rIdRaw = $argv[2] ?? '';
$file   = $argv[3] ?? '';
$year   = isset($argv[4]) ? (int)$argv[4] : null;

if (!$kind || $rIdRaw === '' || !$file) {
    fwrite(STDERR,
        "Usage:\n" .
        "  php bin/ingest-cli.php facility-mapping <report_id|code> <path>\n" .
        "  php bin/ingest-cli.php collection       <report_id|code> <path>\n"
    );
    exit(1);
}
if (!is_file($file)) { fwrite(STDERR, "File not found: $file\n"); exit(1); }

$pdo = db();
$reportId = is_numeric($rIdRaw) ? (int) $rIdRaw : 0;
if (!$reportId) {
    $st = $pdo->prepare("SELECT id FROM reports WHERE code = ? AND deleted_at IS NULL LIMIT 1");
    $st->execute([$rIdRaw]);
    $reportId = (int) ($st->fetchColumn() ?: 0);
}
if (!$reportId) { fwrite(STDERR, "Report not found: $rIdRaw\n"); exit(1); }

$uid = (int) $pdo->query("SELECT id FROM users WHERE email='admin@medmecs.local' LIMIT 1")->fetchColumn();
if (!$uid) { fwrite(STDERR, "sysadmin user not found\n"); exit(1); }

$t0 = microtime(true);
echo "[" . date('H:i:s') . "] $kind ingest -> report #$reportId : " . basename($file)
   . " (" . number_format(filesize($file)/1024/1024, 1) . " MB)\n";

set_time_limit(0);
ini_set('memory_limit', '1G');

$eng = new CollectionEngine();
try {
    switch ($kind) {
        case 'facility-mapping': $res = $eng->ingestFacilityMapping($file, $uid, $reportId); break;
        case 'collection':       $res = $eng->ingestCollection      ($file, $uid, $reportId); break;
        default: fwrite(STDERR, "Unknown kind: $kind\n"); exit(1);
    }
} catch (Throwable $t) {
    fwrite(STDERR, "FAILED: " . $t->getMessage() . "\n"); exit(2);
}

$elapsed = number_format(microtime(true) - $t0, 1);
echo "[" . date('H:i:s') . "] done in {$elapsed}s — upload_id={$res['upload_id']}, "
   . "valid=" . number_format($res['valid']) . ", "
   . "errors=" . number_format($res['errors']) . ", "
   . "total=" . number_format($res['total']) . "\n";
