<?php

declare(strict_types=1);

use App\Application\EnvironmentConfig;
use App\Media\ImageUploadInspector;
use App\Media\MediaScanRunner;

$root = dirname(__DIR__);

if (file_exists($root . '/vendor/autoload.php')) {
    require_once $root . '/vendor/autoload.php';
} else {
    require_once $root . '/src/Application/EnvironmentConfig.php';
    require_once $root . '/src/Media/ImageUploadInspector.php';
    require_once $root . '/src/Media/MediaScanRunner.php';
}

$config = EnvironmentConfig::fromFile($root . '/.env');
$dsn = $config->get('DB_DSN', 'mysql:host=127.0.0.1;port=3306;dbname=zavvion_events;charset=utf8mb4');
$user = $config->get('DB_USERNAME', 'root', ['DB_USER']);
$password = $config->get('DB_PASSWORD', '');
$force = in_array('--force', $argv ?? [], true);
$limit = 100;
foreach ($argv ?? [] as $arg) {
    if (str_starts_with((string) $arg, '--limit=')) {
        $limit = max(1, min(500, (int) substr((string) $arg, 8)));
    }
}

try {
    $pdo = new PDO((string) $dsn, (string) $user, (string) $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);

    $envResolver = static fn (string $key, mixed $default = null): mixed => $config->get($key, $default);
    $runner = new MediaScanRunner($pdo, $root . '/public', new ImageUploadInspector($envResolver));
    echo json_encode($runner->run($limit, $force), JSON_PRETTY_PRINT) . PHP_EOL;
    exit(0);
} catch (Throwable $exception) {
    $payload = [
        'status' => 'error',
        'message' => $exception->getMessage(),
        'ran_at' => date('c'),
    ];
    if ($config->truthy('APP_DEBUG')) {
        $payload['exception'] = get_class($exception);
    }

    fwrite(STDERR, json_encode($payload, JSON_PRETTY_PRINT) . PHP_EOL);
    exit(1);
}
