<?php
declare(strict_types=1);

function eaq_storage_path(string $relative): string {
  $base = __DIR__ . '/../storage';
  $relative = ltrim($relative, '/');
  return $base . '/' . $relative;
}

function eaq_read_json(string $relative, $default) {
  $path = eaq_storage_path($relative);
  if (!file_exists($path)) return $default;
  $json = file_get_contents($path);
  if ($json === false) return $default;
  $data = json_decode($json, true);
  return is_array($data) ? $data : $default;
}

function eaq_write_json(string $relative, $data): void {
  $path = eaq_storage_path($relative);
  $dir = dirname($path);
  if (!is_dir($dir)) mkdir($dir, 0775, true);
  $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  if ($json === false) throw new RuntimeException('Failed to encode JSON.');
  $tmp = $path . '.tmp';
  if (file_put_contents($tmp, $json, LOCK_EX) === false) {
    throw new RuntimeException('Failed to write JSON tmp.');
  }
  rename($tmp, $path);
}

