<?php
if (!function_exists('smurf_fetch_nowplaying_title')) {
function smurf_fetch_nowplaying_title(): string {
    require_once __DIR__ . '/stream_lib.php';
    $cfg = smurf_get_stream_config();
    $title = trim((string)smurf_get_nowplaying_title());
    if ($title !== '') return $title;

    $jsonRaw = smurf_http_get((string)$cfg['status_json_url'], ['Accept: application/json, */*'], 5);
    if ($jsonRaw !== '') {
        $json = json_decode($jsonRaw, true);
        $sources = $json['icestats']['source'] ?? null;
        if ($sources) {
            if (isset($sources['title']) || isset($sources['server_name'])) {
                $sources = [$sources];
            }
            foreach ((array)$sources as $source) {
                $mount = trim((string)($source['listenurl'] ?? $source['server_url'] ?? ''));
                $candidate = trim((string)($source['title'] ?? $source['server_name'] ?? ''));
                if ($candidate !== '') return html_entity_decode($candidate, ENT_QUOTES, 'UTF-8');
            }
        }
    }

    $sevenHtml = smurf_http_get((string)$cfg['seven_html_url'], [], 4);
    if ($sevenHtml !== '') {
        $parts = array_map('trim', explode(',', strip_tags($sevenHtml)));
        if (count($parts) >= 7) {
            $candidate = trim($parts[6]);
            if ($candidate !== '') return html_entity_decode($candidate, ENT_QUOTES, 'UTF-8');
        }
    }

    foreach ([dirname(__DIR__) . '/last-track.txt', dirname(__DIR__) . '/data/nowplaying.txt'] as $file) {
        if (is_file($file)) {
            $candidate = trim((string)file_get_contents($file));
            if ($candidate !== '') return $candidate;
        }
    }
    return 'Underground FX is live — metadata will appear when the stream reports a current title.';
}
}
