<?php
declare(strict_types=1);

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config.php';

function data_file(string $name): string
{
    return DATA_DIR . DIRECTORY_SEPARATOR . $name . '.json';
}

function read_json_data(string $name, array $default = []): array
{
    $file = data_file($name);
    if (!file_exists($file)) {
        write_json_data($name, $default);
        return $default;
    }

    $content = file_get_contents($file);
    if ($content === false || $content === '') {
        return $default;
    }

    $decoded = json_decode($content, true);
    return is_array($decoded) ? $decoded : $default;
}

function write_json_data(string $name, array $data): void
{
    $file = data_file($name);
    file_put_contents($file, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
}

function generate_id(): string
{
    return date('YmdHis') . bin2hex(random_bytes(4));
}
