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

$CFG = [
  'hosts' => [
    ['proto'=>'https','host'=>'studio.simbacast.com',     'port'=>1180,'sid'=>1],
    ['proto'=>'https','host'=>'studio.webradio.solutions', 'port'=>1180,'sid'=>1],
  ],
  'default_cover' => '/v6/img/cover.jpg',
  'http_timeout' => 4,
  'itunes_timeout' => 4,
  'hist_file' => dirname(__DIR__).'/data/history-cache.json',
  'hist_limit' => 30
];

function http_get_json($url,$timeout=4){
  $ctx = stream_context_create([
    'http'=>['timeout'=>$timeout,'ignore_errors'=>true],
    'ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]
  ]);
  $raw = @file_get_contents($url,false,$ctx);
  if($raw===false) return null;
  $j = json_decode($raw,true);
  if(is_array($j)) return $j;
  if(strpos(ltrim($raw),'{')===0||strpos(ltrim($raw),'[')===0){
    $j = json_decode($raw,true);
    if(is_array($j)) return $j;
  }
  return null;
}
function sanitize($s){ return trim(preg_replace('/\s+/',' ',(string)$s)); }
function parse_artist_title($t){
  $p = preg_split('/\s+-\s+|\s+–\s+/u',$t,2);
  if(count($p)===2) return [sanitize($p[0]),sanitize($p[1])];
  return ['',sanitize($t)];
}
function grab_itunes_art($artist,$title,$timeout=4){
  if($title==='') return null;
  $q = urlencode($artist.' '.$title);
  $url = "https://itunes.apple.com/search?term={$q}&entity=song&limit=1";
  $ctx = stream_context_create(['http'=>['timeout'=>$timeout,'ignore_errors'=>true]]);
  $raw = @file_get_contents($url,false,$ctx);
  if(!$raw) return null;
  $data = json_decode($raw,true);
  if(!$data || empty($data['results'])) return null;
  $art = $data['results'][0]['artworkUrl100'] ?? null;
  return $art ? str_replace('100x100bb.jpg','500x500bb.jpg',$art) : null;
}

function fetch_nowplaying($H){
  $sid = (int)($H['sid'] ?? 1);
  $base = "{$H['proto']}://{$H['host']}:{$H['port']}";
  $urls = [
    "{$base}/statistics?json=1",
    "{$base}/stats?json=1",
    "{$base}/stats?sid={$sid}&json=1",
    "{$base}/status-json.xsl",
  ];
  $tried=[];
  foreach($urls as $u){
    $tried[]=$u;
    $j = http_get_json($u,4);
    if(!$j) continue;

    // Shoutcast style
    if(isset($j['songtitle']) || isset($j['streams'])){
      $st = '';
      if(isset($j['songtitle'])) $st = sanitize($j['songtitle']);
      elseif(isset($j['streams'][0]['songtitle'])) $st = sanitize($j['streams'][0]['songtitle']);
      return [$st,$tried];
    }
    // Icecast style
    if(isset($j['icestats'])){
      $src = $j['icestats']['source'] ?? null;
      if(!$src) continue;
      if(isset($src[0])) $src=$src[0];
      $st = sanitize($src['title'] ?? $src['artist'] ?? '');
      return [$st,$tried];
    }
  }
  return ['', $tried];
}

// 1) NOW PLAYING
$tried_all=[];
$now='';
foreach($CFG['hosts'] as $h){
  [$st,$t] = fetch_nowplaying($h);
  $tried_all = array_merge($tried_all,$t);
  if($st!==''){ $now=$st; break; }
}
[$artist,$title] = parse_artist_title($now);

// 2) COVER
$cover = grab_itunes_art($artist,$title,$CFG['itunes_timeout']);
if(!$cover) $cover = $CFG['default_cover'];

// 3) HISTORIQUE PERSISTANT (fichier)
$histFile = $CFG['hist_file'];
if(!is_file($histFile)){
  @mkdir(dirname($histFile),0775,true);
  @file_put_contents($histFile,'[]');
}
$hist = json_decode(@file_get_contents($histFile), true);
if(!is_array($hist)) $hist=[];

// Si nouveau titre => on pousse l’entrée (sans inclure le courant en tête de liste)
$last = $hist[0] ?? null;
$currKey = mb_strtolower($artist.' - '.$title);
$lastKey = $last ? mb_strtolower(($last['artist']??'').' - '.($last['song']??'')) : '';
if($title!=='' && $currKey !== $lastKey){
  // on ajoute L’ANCIEN nowplaying si on l’avait (pas le nouveau),
  // mais comme on ne le connaît pas ici on enregistre simplement la précédente
  // logique : on garde juste une trace des changements successifs
  array_unshift($hist, [
    'artist'  => $artist,
    'song'    => $title,
    'artwork' => $cover,
    'time'    => time()
  ]);
  // dédoublonne
  $seen=[];
  $hist = array_values(array_filter($hist,function($it) use (&$seen){
    $k = mb_strtolower(($it['artist']??'').'|'.($it['song']??''));
    if(isset($seen[$k])) return false;
    $seen[$k]=1; return true;
  }));
  // limite
  if(count($hist) > $CFG['hist_limit']) $hist = array_slice($hist,0,$CFG['hist_limit']);
  @file_put_contents($histFile, json_encode($hist, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
}

// On renvoie l’historique SANS le titre courant
$historyOut = array_values(array_filter($hist,function($it) use($artist,$title){
  return !(mb_strtolower($it['artist'])===mb_strtolower($artist) && mb_strtolower($it['song'])===mb_strtolower($title));
}));

// 4) Badge lyrics (optionnel)
$lyricsAvailable = false;
if($artist!=='' && $title!==''){
  $p = dirname(__DIR__).'/data/lyrics/'.$artist.' - '.$title.'.txt';
  if(is_file($p)) $lyricsAvailable = true;
  else {
    $url = "https://api.lyrics.ovh/v1/".rawurlencode($artist)."/".rawurlencode($title);
    $ctx = stream_context_create(['http'=>['timeout'=>3,'ignore_errors'=>true]]);
    $raw = @file_get_contents($url,false,$ctx);
    $j = $raw ? json_decode($raw,true) : null;
    if($j && !empty($j['lyrics'])) $lyricsAvailable = true;
  }
}

echo json_encode([
  'artist' => $artist,
  'song'   => $title,
  'artwork'=> $cover,
  'history'=> $historyOut,
  'lyrics_available'=>$lyricsAvailable,
  '_debug'=>['tried'=>$tried_all]
], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
