<?php
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

require_once __DIR__ . '/../includes/stream_lib.php';

$cacheFile = __DIR__ . '/../data/icecast_stats_cache.json';
$cacheTtl  = 15;

function smurf_stats_read_cache(string $file, int $ttl): ?array {
  if (!is_file($file)) return null;
  if (time() - (int)filemtime($file) > $ttl) return null;
  $raw = @file_get_contents($file);
  $data = $raw ? json_decode($raw, true) : null;
  return is_array($data) ? $data : null;
}

function smurf_stats_write_cache(string $file, array $data): void {
  $dir = dirname($file);
  if (!is_dir($dir)) @mkdir($dir, 0755, true);
  @file_put_contents($file, json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE), LOCK_EX);
}

$cached = smurf_stats_read_cache($cacheFile, $cacheTtl);
if ($cached) {
  echo json_encode($cached, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  exit;
}

$source = smurf_get_preferred_source();
if (!is_array($source)) {
  if (is_file($cacheFile)) {
    $stale = json_decode((string)@file_get_contents($cacheFile), true);
    if (is_array($stale)) {
      $stale['_warning'] = 'Icecast fetch failed (served stale)';
      echo json_encode($stale, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
      exit;
    }
  }

  http_response_code(503);
  echo json_encode(['ok' => false, 'error' => 'Icecast fetch failed'], JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
  exit;
}

$out = [
  'ok' => true,
  'listeners' => (int)($source['listeners'] ?? 0),
  'mount' => (string)($source['mount'] ?? ''),
  'title' => (string)($source['title'] ?? ''),
  'stream_start' => (string)($source['stream_start'] ?? ''),
  'ts' => time(),
];

smurf_stats_write_cache($cacheFile, $out);
echo json_encode($out, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
