<?php

declare(strict_types=1);

function readJsonFile(string $path, array $default = []): array
{
    if (!is_file($path)) {
        return $default;
    }

    $raw = file_get_contents($path);
    if ($raw === false || trim($raw) === '') {
        return $default;
    }

    $decoded = json_decode($raw, true);

    return is_array($decoded) ? $decoded : $default;
}

function writeJsonFile(string $path, array $data): void
{
    $dir = dirname($path);
    if (!is_dir($dir)) {
        if (!mkdir($dir, 02775, true) && !is_dir($dir)) {
            throw new RuntimeException('Cannot create directory: ' . $dir);
        }
        @chmod($dir, 02775);
    }

    $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    if ($json === false) {
        throw new RuntimeException('Cannot encode JSON for file: ' . $path);
    }

    $written = file_put_contents(
        $path,
        $json,
        LOCK_EX
    );

    if ($written === false) {
        throw new RuntimeException('Cannot write JSON file: ' . $path);
    }

    // Runtime files are shared by the web handler and the CLI cron user.
    @chmod($path, 0664);
}

function isEventProcessed(string $eventId): bool
{
    $stateFile = (string) config('STATE_FILE');
    $state = readJsonFile($stateFile, ['processed_events' => []]);

    return isset($state['processed_events'][$eventId]);
}

function markEventProcessed(string $eventId): void
{
    $stateFile = (string) config('STATE_FILE');
    $state = readJsonFile($stateFile, ['processed_events' => []]);
    $state['processed_events'][$eventId] = time();

    if (count($state['processed_events']) > 500) {
        asort($state['processed_events']);
        $state['processed_events'] = array_slice($state['processed_events'], -500, null, true);
    }

    writeJsonFile($stateFile, $state);
}

function unmarkEventProcessed(string $eventId): void
{
    $stateFile = (string) config('STATE_FILE');
    $state = readJsonFile($stateFile, ['processed_events' => []]);
    if (!isset($state['processed_events'][$eventId])) {
        return;
    }

    unset($state['processed_events'][$eventId]);
    writeJsonFile($stateFile, $state);
}
