<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit(1);
}

/**
 * Cache cleanup — run via cron daily:
 *   0 2 * * * php /path/to/redirect/cleanup-cache.php
 *
 * Removes stale SRP cache files older than the configured TTLs:
 *   geo_*.json   — 7 days (country data rarely changes)
 *   vpn_*.json   — 7 days (IP reputation is stable)
 *   click_*.json — 1 day  (dedup window is only 5 min)
 *   filter_url.txt — 30 days (runtime overrides should persist)
 */

const CACHE_DIR_NAME = 'srp_bb';

$cacheDir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR)
    . DIRECTORY_SEPARATOR . CACHE_DIR_NAME;

if (!is_dir($cacheDir)) {
    if (!mkdir($cacheDir, 0750, true) && !is_dir($cacheDir)) {
        fwrite(STDERR, 'Cannot create cache directory: ' . $cacheDir . PHP_EOL);
        exit(1);
    }
    echo 'Created cache directory: ' . $cacheDir . PHP_EOL;
}

$now = time();
$removed = 0;
$errors = 0;

$rules = [
    'geo_'    => 7 * 86400,   // 7 days
    'vpn_'    => 7 * 86400,   // 7 days
    'click_'  => 86400,       // 1 day
    'sl_'     => 3600,        // 1 hour  (srp_shortlinks_find() TTL is 5 min; keep margin)
    'filter_' => 30 * 86400,  // 30 days
];

$files = scandir($cacheDir);
if ($files === false) {
    fwrite(STDERR, 'Cannot scan cache directory: ' . $cacheDir . PHP_EOL);
    exit(1);
}

foreach ($files as $file) {
    if ($file === '.' || $file === '..') {
        continue;
    }

    $path = $cacheDir . DIRECTORY_SEPARATOR . $file;

    if (!is_file($path)) {
        continue;
    }

    $matchedTtl = null;
    foreach ($rules as $prefix => $ttl) {
        if (str_starts_with($file, $prefix)) {
            $matchedTtl = $ttl;
            break;
        }
    }

    if ($matchedTtl === null) {
        continue; // unknown file — leave it
    }

    $age = $now - filemtime($path);
    if ($age > $matchedTtl) {
        if (@unlink($path)) {
            $removed++;
        } else {
            $errors++;
            fwrite(STDERR, 'Failed to remove: ' . $path . PHP_EOL);
        }
    }
}

echo sprintf(
    'Cleaned %d files, %d errors from %s' . PHP_EOL,
    $removed,
    $errors,
    $cacheDir,
);

exit($errors > 0 ? 1 : 0);
