<?php
function smurf_read_json(string $path, $default) {
  if (!file_exists($path)) return $default;
  $raw = file_get_contents($path);
  $data = json_decode($raw, true);
  return is_null($data) ? $default : $data;
}

function smurf_write_json(string $path, $data): bool {
  $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  if ($json === false) return false;
  // simple backup
  if (file_exists($path)) @copy($path, $path . ".bak");
  return file_put_contents($path, $json . "\n") !== false;
}

/**
 * Parse blocks like:
 *   Key: value
 *   Key2: value
 *   ---
 */
function smurf_parse_blocks(string $path): array {
  if (!file_exists($path)) return [];
  $raw = trim((string)file_get_contents($path));
  if ($raw === '') return [];
  $chunks = preg_split("/\n---\s*\n/", $raw);
  $out = [];
  foreach ($chunks as $chunk) {
    $chunk = trim($chunk);
    if ($chunk === '') continue;
    $lines = preg_split("/\R/", $chunk);
    $entry = ['_raw' => $chunk];
    foreach ($lines as $line) {
      if (strpos($line, ':') === false) continue;
      [$k,$v] = explode(':', $line, 2);
      $k = trim($k);
      $v = trim($v);
      if ($k !== '') $entry[$k] = $v;
    }
    $out[] = $entry;
  }
  // newest first (because we append to file)
  return array_reverse($out);
}

function smurf_delete_block(string $path, int $index_from_newest): bool {
  // We parse newest-first, but file is oldest-first, so we need to map index.
  if (!file_exists($path)) return false;
  $raw = trim((string)file_get_contents($path));
  if ($raw === '') return false;

  $chunks = preg_split("/\n---\s*\n/", $raw);
  $chunks = array_values(array_filter(array_map('trim',$chunks), fn($c)=>$c!==''));
  $count = count($chunks);
  if ($count === 0) return false;

  $index_from_oldest = ($count - 1) - $index_from_newest;
  if ($index_from_oldest < 0 || $index_from_oldest >= $count) return false;

  array_splice($chunks, $index_from_oldest, 1);
  $newRaw = $chunks ? implode("\n---\n", $chunks) . "\n---\n" : "";
  if (file_exists($path)) @copy($path, $path . ".bak");
  return file_put_contents($path, $newRaw) !== false;
}

function smurf_clear_file(string $path): bool {
  if (file_exists($path)) @copy($path, $path . ".bak");
  return file_put_contents($path, "") !== false;
}

function smurf_h(string $s): string {
  return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}
