<?php

require_once __DIR__ . '/utils.php';

function getDataDirectory(): string {
    return __DIR__ . '/../data';
}

function getDataFilePath(string $filename): string {
    return getDataDirectory() . '/' . $filename;
}

function ensureDataDirectory(): void {
    $dataDir = getDataDirectory();
    if (!is_dir($dataDir)) {
        mkdir($dataDir, 0755, true);
    }
}

function readJsonFile(string $filename) {
    $filepath = getDataFilePath($filename);
    if (!file_exists($filepath)) {
        return [];
    }
    $fp = fopen($filepath, 'rb');
    if ($fp === false) {
        return [];
    }
    if (!flock($fp, LOCK_SH)) {
        fclose($fp);
        return [];
    }
    $content = stream_get_contents($fp);
    flock($fp, LOCK_UN);
    fclose($fp);
    if ($content === false || $content === '') {
        return [];
    }
    $decoded = json_decode($content, true);
    return $decoded ?? [];
}

function writeJsonFile(string $filename, $data): bool {
    ensureDataDirectory();
    $filepath = getDataFilePath($filename);
    $fp = fopen($filepath, 'c+');
    if ($fp === false) {
        return false;
    }
    if (!flock($fp, LOCK_EX)) {
        fclose($fp);
        return false;
    }
    $json = json_encode($data, JSON_PRETTY_PRINT | familyHubJsonEncodeShellFlags());
    if ($json === false) {
        flock($fp, LOCK_UN);
        fclose($fp);
        return false;
    }
    ftruncate($fp, 0);
    rewind($fp);
    $written = fwrite($fp, $json);
    fflush($fp);
    flock($fp, LOCK_UN);
    fclose($fp);
    return $written !== false;
}
