<?php
/**
 * Rebuild the Collection Dashboard JSON snapshot cache (collection_stats).
 *
 *   php bin/rebuild-cache.php            # all collection_dashboard reports
 *   php bin/rebuild-cache.php 1          # one report by id
 *   php bin/rebuild-cache.php COLL-DASH  # one report by code
 *
 * Run this after changing any cached aggregation in the engine so the
 * unfiltered (cache-backed) dashboard views match the live (filtered) ones.
 */
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';

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

$pdo = db();
$arg = $argv[1] ?? 'all';

$reportIds = [];
if ($arg === 'all') {
    $reportIds = $pdo->query(
        "SELECT id FROM reports WHERE handler='collection_dashboard' AND deleted_at IS NULL ORDER BY id"
    )->fetchAll(PDO::FETCH_COLUMN);
} elseif (is_numeric($arg)) {
    $reportIds[] = (int) $arg;
} else {
    $st = $pdo->prepare("SELECT id FROM reports WHERE code=? AND deleted_at IS NULL LIMIT 1");
    $st->execute([$arg]);
    $rid = (int) ($st->fetchColumn() ?: 0);
    if ($rid) $reportIds[] = $rid;
}

if (!$reportIds) { fwrite(STDERR, "No matching collection_dashboard report for: $arg\n"); exit(1); }

$eng = new CollectionEngine();
foreach ($reportIds as $rid) {
    $rid = (int) $rid;
    $st = $pdo->prepare("SELECT id FROM collection_uploads
                          WHERE report_id=? AND kind='collection' AND status='completed'
                          ORDER BY completed_at DESC LIMIT 1");
    $st->execute([$rid]);
    $uploadId = (int) ($st->fetchColumn() ?: 0);
    if (!$uploadId) { echo "report #$rid: no completed collection upload — skipped\n"; continue; }

    $t0 = microtime(true);
    echo "Rebuilding cache for report #$rid, upload #$uploadId...\n";
    $eng->computeAndCacheStats($uploadId, $rid);
    echo "  Done in " . number_format(microtime(true) - $t0, 1) . "s\n";
}
echo "All requested caches rebuilt.\n";
