<?php
// /api/stats.php
// Returns current listener count for Almost Heaven (prefers /stream, fallback /autodj).
header('Content-Type: application/json; charset=utf-8');

$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);
  return $raw ? json_decode($raw, true) : 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) {
  $body = false; $code = 0;
  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 => 'Almost HeavenSite/1.0',
    ]);
    $body = curl_exec($ch);
    $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
  } else {
    $context = stream_context_create(['http' => ['timeout' => 5, 'header' => "User-Agent: Almost HeavenSite/1.0\r\n"]]);
    $body = @file_get_contents($url, false, $context);
    if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $m)) $code = (int)$m[1];
  }
  if ($body === false || $code >= 400) return null;
  $j = json_decode($body, true);
  return is_array($j) ? $j : null;
}

function sourcesFromIcestats($icestats) {
  $src = $icestats['source'] ?? [];
  $out = [];
  if (isset($src[0])) $out = $src;
  elseif (is_array($src)) $out = [$src];
  return $out;
}

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'])) {
  // stale cache fallback
  if (file_exists($cacheFile)) {
    $stale = json_decode(@file_get_contents($cacheFile), true);
    if (is_array($stale)) { $stale['_warning'] = 'Icecast fetch failed (served stale)'; echo json_encode($stale); exit; }
  }
  http_response_code(503);
  echo json_encode(['ok'=>false,'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);
