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

$ICECAST_STATUS_URL = 'http://cr3.broadcasturself.com:1982/status-json.xsl';
$preferMount = '/stream';
$fallbackMounts = ['/autodj','/autodj2'];
$cacheFile = __DIR__ . '/../data/icecast_stats_cache.json';
$cacheTtl  = 15;

function readCache($file, $ttl) {
  if (!file_exists($file)) return null;
  if (time() - filemtime($file) > $ttl) return null;
  $raw = @file_get_contents($file);
  $decoded = $raw ? json_decode($raw, true) : null;
  return is_array($decoded) ? $decoded : null;
}
function writeCache($file, $data) {
  $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);
}
function httpGetJson($url) {
  if (function_exists('curl_init')) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_CONNECTTIMEOUT => 3,
      CURLOPT_TIMEOUT => 5,
      CURLOPT_USERAGENT => 'ThunderMountainRadioSite/1.1',
    ]);
    $body = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($body === false || $code >= 400) return null;
  } else {
    $ctx = stream_context_create(['http' => [
      'method' => 'GET',
      'timeout' => 5,
      'ignore_errors' => true,
      'header' => "User-Agent: ThunderMountainRadioSite/1.1
",
    ]]);
    $body = @file_get_contents($url, false, $ctx);
    if ($body === false) return null;
  }
  $j = json_decode($body, true);
  return is_array($j) ? $j : null;
}
function sourcesFromIcestats($icestats) {
  $src = $icestats['source'] ?? [];
  if (isset($src[0]) && is_array($src[0])) return $src;
  return is_array($src) && $src ? [$src] : [];
}
function mountFromListenUrl($listenurl) {
  if (!$listenurl) return '';
  $parts = parse_url($listenurl);
  return $parts['path'] ?? '';
}
$cached = readCache($cacheFile, $cacheTtl);
if ($cached) { echo json_encode($cached); exit; }
$j = httpGetJson($ICECAST_STATUS_URL);
if (!$j || !isset($j['icestats'])) {
  if (file_exists($cacheFile)) {
    $stale = json_decode((string)@file_get_contents($cacheFile), true);
    if (is_array($stale) && array_key_exists('listeners', $stale)) { $stale['_warning'] = 'Icecast fetch failed (served stale)'; echo json_encode($stale); exit; }
  }
  echo json_encode(['ok'=>false,'listeners'=>0,'error'=>'Icecast fetch failed']);
  exit;
}
$ic = $j['icestats'];
$sources = sourcesFromIcestats($ic);
$pick = null;
foreach ($sources as $s) { if (mountFromListenUrl($s['listenurl'] ?? '') === $preferMount) { $pick = $s; break; } }
if (!$pick) {
  foreach ($fallbackMounts as $m) { foreach ($sources as $s) { if (mountFromListenUrl($s['listenurl'] ?? '') === $m) { $pick = $s; break 2; } } }
}
if (!$pick && !empty($sources)) $pick = $sources[0];
$listeners = isset($pick['listeners']) ? (int)$pick['listeners'] : (isset($ic['listeners']) ? (int)$ic['listeners'] : 0);
$out = ['ok'=>true,'listeners'=>$listeners,'mount'=>mountFromListenUrl($pick['listenurl'] ?? ''),'ts'=>time()];
writeCache($cacheFile, $out);
echo json_encode($out);
