<?php
/**
 * Radio Browser API Proxy (nur DE-Sender).
 * Liefert Sender mit Stream-URL, Favicon und Metadaten.
 */
require __DIR__ . '/../config.php';
require FUNCTIONS_ROOT . '/functions_common.php';

header('Content-Type: application/json; charset=utf-8');

const RADIO_BROWSER_CACHE_TTL = 1800; // 30 Minuten

function radio_api_cache_file(): string
{
    return rtrim(STORAGE_ROOT, '/\\') . '/cache/radio_browser_de.json';
}

function radio_api_context()
{
    return stream_context_create([
        'http' => [
            'timeout' => 8,
            'header' => "User-Agent: Wecker-Radio/1.0 (PHP)\r\n"
        ]
    ]);
}

function radio_api_valid_http_url(?string $url): ?string
{
    $url = trim((string) $url);
    if ($url === '') return null;
    if (filter_var($url, FILTER_VALIDATE_URL) === false) return null;
    $parts = parse_url($url);
    $scheme = strtolower((string) ($parts['scheme'] ?? ''));
    if (!in_array($scheme, ['http', 'https'], true)) return null;
    return $url;
}

function radio_api_normalize(array $rows): array
{
    $out = [];
    $seen = [];
    foreach ($rows as $r) {
        $name = trim((string) ($r['name'] ?? ''));
        $stream = radio_api_valid_http_url((string) ($r['url_resolved'] ?? $r['url'] ?? ''));
        if ($name === '' || $stream === null) {
            continue;
        }
        $key = md5(strtolower($name) . '|' . strtolower($stream));
        if (isset($seen[$key])) {
            continue;
        }
        $seen[$key] = true;
        $out[] = [
            'id'         => (string) ($r['stationuuid'] ?? $key),
            'name'       => $name,
            'stream_url' => $stream,
            'favicon'    => radio_api_valid_http_url((string) ($r['favicon'] ?? '')),
            'homepage'   => radio_api_valid_http_url((string) ($r['homepage'] ?? '')),
            'tags'       => trim((string) ($r['tags'] ?? '')),
            'codec'      => trim((string) ($r['codec'] ?? '')),
            'bitrate'    => isset($r['bitrate']) ? (int) $r['bitrate'] : null,
        ];
    }
    return $out;
}

function radio_api_load_cache(bool $allowStale = false): array
{
    $file = radio_api_cache_file();
    if (!is_file($file) || !is_readable($file)) {
        return [];
    }
    $raw = @file_get_contents($file);
    if ($raw === false || $raw === '') {
        return [];
    }
    $payload = @json_decode($raw, true);
    if (!is_array($payload) || empty($payload['stations']) || !is_array($payload['stations'])) {
        return [];
    }
    $savedAt = isset($payload['saved_at']) ? (int) $payload['saved_at'] : 0;
    $fresh = $savedAt > 0 && (time() - $savedAt) <= RADIO_BROWSER_CACHE_TTL;
    if ($fresh || $allowStale) {
        return $payload['stations'];
    }
    return [];
}

function radio_api_save_cache(array $stations): void
{
    $file = radio_api_cache_file();
    $dir = dirname($file);
    if (!is_dir($dir)) {
        @mkdir($dir, 0755, true);
    }
    $payload = [
        'saved_at' => time(),
        'stations' => $stations
    ];
    @file_put_contents($file, json_encode($payload), LOCK_EX);
}

function radio_api_fetch_de(): array
{
    $query = http_build_query([
        'hidebroken' => 'true',
        'order'      => 'votes',
        'reverse'    => 'true',
        'limit'      => '500'
    ]);
    $urls = [
        'https://de1.api.radio-browser.info/json/stations/bycountrycodeexact/DE?' . $query,
        'https://all.api.radio-browser.info/json/stations/bycountrycodeexact/DE?' . $query,
    ];
    $ctx = radio_api_context();
    foreach ($urls as $url) {
        $raw = @file_get_contents($url, false, $ctx);
        if ($raw === false || $raw === '') continue;
        $decoded = @json_decode($raw, true);
        if (!is_array($decoded)) continue;
        $stations = radio_api_normalize($decoded);
        if (!empty($stations)) {
            return $stations;
        }
    }
    return [];
}

try {
    $action = $_GET['action'] ?? $_POST['action'] ?? 'list_de';
    if ($action !== 'list_de') {
        function_json_antwort(false, [], 'Unbekannte Aktion');
    }

    $cached = radio_api_load_cache(false);
    if (!empty($cached)) {
        function_json_antwort(true, ['stations' => $cached]);
    }

    $stations = radio_api_fetch_de();
    if (!empty($stations)) {
        radio_api_save_cache($stations);
        function_json_antwort(true, ['stations' => $stations]);
    }

    $stale = radio_api_load_cache(true);
    if (!empty($stale)) {
        function_json_antwort(true, ['stations' => $stale]);
    }

    function_json_antwort(false, [], 'Radio Browser nicht erreichbar');
} catch (Throwable $e) {
    error_log('[api_radio] ' . $e->getMessage());
    function_json_antwort(false, [], 'Serverfehler');
}

