<?php
/**
 * Sonora — test_stream.php
 * Testa se o sistema de stream de áudio está funcionando
 * ⚠️ APAGUE APÓS O TESTE!
 */
set_time_limit(30);

echo "<!DOCTYPE html><html lang='pt-BR'><head><meta charset='UTF-8'><title>Teste Stream</title>
<style>
  body{font-family:monospace;background:#0a0a0f;color:#f0f0f8;padding:30px;line-height:1.9}
  .ok{color:#00e5a0}.err{color:#ff4d6d}.warn{color:#f7c16f}
  pre{background:#16161f;border:1px solid #2a2a3a;border-radius:8px;padding:14px;overflow-x:auto;white-space:pre-wrap;word-break:break-all;font-size:12px}
  h2{color:#00e5a0;font-family:sans-serif}
  h3{color:#7c6ff7;font-family:sans-serif;margin:18px 0 6px}
  .box{background:#16161f;border-left:3px solid #00e5a0;padding:12px 16px;margin:10px 0;border-radius:0 8px 8px 0}
  audio{width:100%;margin:10px 0;border-radius:8px}
  .tag{display:inline-block;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:700}
  .tag-ok{background:rgba(0,229,160,.15);color:#00e5a0;border:1px solid rgba(0,229,160,.3)}
  .tag-err{background:rgba(255,77,109,.1);color:#ff4d6d;border:1px solid rgba(255,77,109,.25)}
  .tag-warn{background:rgba(247,193,111,.1);color:#f7c16f;border:1px solid rgba(247,193,111,.25)}
</style></head><body>
<h2>🎵 Sonora — Diagnóstico de Stream de Áudio</h2>
<p class='warn'>⚠ Arquivo temporário de diagnóstico — delete após o teste!</p>";

// Vídeo de teste: "Me at the zoo" — 1º vídeo do YouTube, público garantido
$testId  = 'jNQXAC9IVRw';
$testId2 = 'BaW_jenozKc'; // "Introduction to PHP"
$base    = __DIR__;

// ── Função cURL ───────────────────────────────────────────────────────────────
function do_curl($url, $timeout=8) {
    $ch = curl_init();
    curl_setopt_array($ch,[
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => $timeout,
        CURLOPT_CONNECTTIMEOUT => 4,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0 Safari/537.36',
        CURLOPT_HTTPHEADER     => ['Accept: application/json','Accept-Language: pt-BR,pt;q=0.9'],
    ]);
    $body = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
    curl_close($ch);
    return ['body'=>$body,'code'=>$code,'time'=>round($time,2)];
}

// ── Teste 1: Invidious ────────────────────────────────────────────────────────
echo "<h3>1️⃣ Testando Invidious API</h3>";

$instances = [
    'https://inv.nadeko.net',
    'https://invidious.nerdvpn.de',
    'https://yewtu.be',
    'https://invidious.privacyredirect.com',
    'https://invidious.lunar.icu',
    'https://iv.ggtyler.dev',
    'https://invidious.privacydev.net',
];
shuffle($instances);

$invAudioUrl = null;
$invWorked   = false;

foreach ($instances as $inv) {
    echo "<p>Testando <code>$inv</code>... "; flush();
    $r = do_curl("$inv/api/v1/videos/$testId?fields=adaptiveFormats,formatStreams");
    if ($r['code'] !== 200 || !$r['body']) {
        echo "<span class='tag tag-err'>HTTP {$r['code']} ({$r['time']}s)</span></p>"; continue;
    }
    $data = json_decode($r['body'], true);
    if (!$data || isset($data['error'])) {
        echo "<span class='tag tag-err'>JSON inválido</span></p>"; continue;
    }
    $fmts = array_merge($data['adaptiveFormats']??[], $data['formatStreams']??[]);
    $best = null; $bestPrio = 99;
    foreach ($fmts as $f) {
        $type = strtolower($f['type']??'');
        $url  = $f['url']??'';
        if (!$url || strpos($url,'http')!==0) continue;
        if (strpos($type,'audio')===false && strpos($type,'m4a')===false && strpos($type,'opus')===false) continue;
        if (strpos($type,'avc')!==false) continue;
        $prio=99;
        if(strpos($type,'m4a')!==false) $prio=1;
        elseif(strpos($type,'opus')!==false) $prio=2;
        elseif(strpos($type,'webm')!==false) $prio=3;
        else $prio=4;
        if($prio<$bestPrio){$best=$url;$bestPrio=$prio;}
    }
    if ($best) {
        $invAudioUrl = $best;
        $invWorked   = true;
        echo "<span class='tag tag-ok'>✅ OK ({$r['time']}s)</span></p>";
        echo "<p class='ok'>URL de áudio obtida! Tipo prio=$bestPrio, ".strlen($best)." chars</p>";
        break;
    }
    echo "<span class='tag tag-warn'>Sem áudio nos formatos</span></p>";
}

if (!$invWorked) {
    echo "<p class='err'>❌ Nenhuma instância Invidious retornou URL de áudio.</p>";
}

// ── Teste 2: Piped API ────────────────────────────────────────────────────────
echo "<h3>2️⃣ Testando Piped API</h3>";

$pipedInstances = [
    'https://pipedapi.kavin.rocks',
    'https://pipedapi.adminforge.de',
    'https://piped-api.garudalinux.org',
];
shuffle($pipedInstances);

$pipedAudioUrl = null;
$pipedWorked   = false;

foreach ($pipedInstances as $piped) {
    echo "<p>Testando <code>$piped</code>... "; flush();
    $r = do_curl("$piped/streams/$testId");
    if ($r['code'] !== 200 || !$r['body']) {
        echo "<span class='tag tag-err'>HTTP {$r['code']} ({$r['time']}s)</span></p>"; continue;
    }
    $data = json_decode($r['body'], true);
    if (empty($data['audioStreams'])) {
        echo "<span class='tag tag-warn'>Sem audioStreams</span></p>"; continue;
    }
    $streams = $data['audioStreams'];
    usort($streams, fn($a,$b) => ($b['bitrate']??0) - ($a['bitrate']??0));
    foreach ($streams as $s) {
        $url = $s['url']??'';
        if ($url && strpos($url,'http')===0) {
            $pipedAudioUrl = $url;
            $pipedWorked   = true;
            echo "<span class='tag tag-ok'>✅ OK ({$r['time']}s) - {$s['bitrate']}bps {$s['codec']}</span></p>";
            break;
        }
    }
    if ($pipedWorked) break;
    echo "<span class='tag tag-warn'>URLs inválidas</span></p>";
}

if (!$pipedWorked) {
    echo "<p class='err'>❌ Nenhuma instância Piped funcionou.</p>";
}

// ── Teste 3: youtube-dl ───────────────────────────────────────────────────────
echo "<h3>3️⃣ Testando youtube-dl / yt-dlp local</h3>";

$ytdlpPath = null;
$ytdlAudioUrl = null;

$candidates = [
    $base . '/yt-dlp-run',
    $base . '/youtube-dl',
    $base . '/yt-dlp',
    '/usr/local/bin/yt-dlp',
    '/usr/bin/youtube-dl',
];
foreach ($candidates as $c2) {
    if (file_exists($c2)) { $ytdlpPath = $c2; break; }
}

if ($ytdlpPath) {
    $python = '/bin/python3.6';
    $isScript = !is_executable($ytdlpPath) || strpos($ytdlpPath,'youtube-dl')!==false;

    // Detecta se é script python ou executável
    $firstBytes = file_get_contents($ytdlpPath, false, null, 0, 10);
    $isPython   = strpos($firstBytes,'#!/bin') !== false || strpos($firstBytes,'#!') === 0;

    echo "<p>Encontrado: <code>$ytdlpPath</code></p>";

    if (basename($ytdlpPath) === 'yt-dlp-run') {
        $cmd = "$ytdlpPath --version 2>&1";
    } elseif ($isPython) {
        $cmd = "$python $ytdlpPath --version 2>&1";
    } else {
        $cmd = "$ytdlpPath --version 2>&1";
    }

    $ver = trim(shell_exec($cmd)?:'');
    echo "<p>Versão: <code>$ver</code></p>";

    if ($ver && strpos($ver,'Error')===false && strlen($ver)<25) {
        echo "<p>Tentando extrair URL...</p>"; flush();
        if (basename($ytdlpPath) === 'yt-dlp-run') {
            $extractCmd = "$ytdlpPath --no-check-certificate --no-playlist -f 'bestaudio/best' --get-url 'https://www.youtube.com/watch?v=$testId' 2>&1";
        } else {
            $extractCmd = "$python $ytdlpPath --no-check-certificate --no-playlist -f 'bestaudio/best' --get-url 'https://www.youtube.com/watch?v=$testId' 2>&1";
        }
        $ytOut = trim(shell_exec($extractCmd)?:'');
        if (strlen($ytOut)>50 && strpos($ytOut,'http')===0) {
            $ytdlAudioUrl = $ytOut;
            echo "<p class='ok'>✅ youtube-dl funcionando! URL obtida.</p>";
        } else {
            echo "<pre>".htmlspecialchars(substr($ytOut,0,300))."</pre>";
            echo "<p class='warn'>⚠ Extração bloqueada (normal — IP do servidor na lista do YouTube).</p>";
        }
    }
} else {
    echo "<p class='warn'>⚠ Nenhum extrator local encontrado.</p>";
}

// ── Resultado ─────────────────────────────────────────────────────────────────
$bestUrl = $invAudioUrl ?: $pipedAudioUrl ?: $ytdlAudioUrl;

echo "<h3>📊 Resultado</h3>";
echo "<table style='border-collapse:collapse;width:100%'>";
echo "<tr><td style='padding:8px 14px;border-bottom:1px solid #2a2a3a'>Invidious API</td><td style='padding:8px 14px;border-bottom:1px solid #2a2a3a'><span class='tag ".($invWorked?'tag-ok':'tag-err')."'>".($invWorked?'✅ FUNCIONANDO':'❌ FALHOU')."</span></td></tr>";
echo "<tr><td style='padding:8px 14px;border-bottom:1px solid #2a2a3a'>Piped API</td><td style='padding:8px 14px;border-bottom:1px solid #2a2a3a'><span class='tag ".($pipedWorked?'tag-ok':'tag-err')."'>".($pipedWorked?'✅ FUNCIONANDO':'❌ FALHOU')."</span></td></tr>";
echo "<tr><td style='padding:8px 14px'>youtube-dl local</td><td style='padding:8px 14px'><span class='tag ".($ytdlAudioUrl?'tag-ok':'tag-warn')."'>".($ytdlAudioUrl?'✅ FUNCIONANDO':'⚠ BLOQUEADO')."</span></td></tr>";
echo "</table>";

if ($bestUrl) {
    echo "<br><div class='box'>";
    echo "<p class='ok'><strong>✅ Sistema de stream funcionando!</strong></p>";
    echo "<p>O indicador no player deve mostrar <strong style='color:#00e5a0'>ÁUDIO</strong> ao tocar uma música.</p>";
    echo "<p>Reprodução em segundo plano <strong class='ok'>ativa</strong>.</p>";
    echo "</div>";

    // Player de teste
    echo "<h3>🎵 Player de teste (HTML5 Audio)</h3>";
    echo "<p class='warn'>Se tocar abaixo, o modo ÁUDIO vai funcionar no player:</p>";
    echo "<audio controls preload='none'>";
    echo "<source src='".htmlspecialchars($bestUrl)."'>";
    echo "Seu browser não suporta audio HTML5.";
    echo "</audio>";
    echo "<p class='mut' style='font-size:11px'>URL: ".htmlspecialchars(substr($bestUrl,0,80))."...</p>";

} else {
    echo "<br><div class='box' style='border-color:#ff4d6d'>";
    echo "<p class='err'><strong>❌ Nenhuma fonte de stream disponível.</strong></p>";
    echo "<p>O player vai usar o modo IFrame (VÍDEO) automaticamente.</p>";
    echo "<p class='warn'>Verifique se o servidor tem acesso à internet (curl habilitado).</p>";
    $curlTest = do_curl('https://httpbin.org/get');
    echo "<p>Teste de conectividade (httpbin): <span class='tag ".($curlTest['code']===200?'tag-ok':'tag-err')."'>HTTP {$curlTest['code']}</span></p>";
    echo "</div>";
}

echo "<br><p class='err'><strong>🗑 DELETE: test_stream.php</strong></p>";
echo "</body></html>";
