<?php
declare(strict_types=1);

require_once __DIR__ . '/app.php';

function fetch_icecast_status(string $baseUrl, string $user, string $pass): ?array {
    $url = rtrim($baseUrl, '/') . '/status-json.xsl';
    if (!function_exists('curl_init')) {
        return null;
    }
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT => 8,
        CURLOPT_USERPWD => $user . ':' . $pass,
    ]);
    $response = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($response === false || $status >= 400) {
        return null;
    }
    $decoded = json_decode($response, true);
    return is_array($decoded) ? $decoded : null;
}

function get_now_playing_data(): array {
    $cacheFile = CACHE_DIR . '/icecast.json';
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < 8)) {
        $cached = json_decode((string) file_get_contents($cacheFile), true);
        if (is_array($cached)) {
            return $cached;
        }
    }

    $streamsFile = SECURE_CONFIG_DIR . '/streams.php';
    if (!file_exists($streamsFile)) {
        return [];
    }

    $streams = include $streamsFile;
    if (!is_array($streams)) {
        return [];
    }

    $results = [];
    foreach ($streams as $stream) {
        $name = (string) ($stream['name'] ?? 'Station');
        $url = (string) ($stream['url'] ?? '');
        $user = (string) ($stream['user'] ?? '');
        $pass = (string) ($stream['pass'] ?? '');

        if ($url === '' || $user === '' || $pass === '' || $pass === 'CHANGE_ME') {
            continue;
        }

        $status = fetch_icecast_status($url, $user, $pass);
        if (!$status || empty($status['icestats'])) {
            $results[] = [
                'station' => $name,
                'status' => 'offline',
                'title' => 'Stream unavailable',
                'listeners' => 0,
                'mount' => '',
            ];
            continue;
        }

        $icestats = $status['icestats'];
        $sources = $icestats['source'] ?? [];
        if (isset($sources['listenurl']) || isset($sources['server_name'])) {
            $sources = [$sources];
        }

        $chosen = null;
        $priority = ['/stream', '/stream2', '/autodj'];
        foreach ($priority as $mount) {
            foreach ($sources as $source) {
                $listenurl = (string) ($source['listenurl'] ?? '');
                if ($listenurl !== '' && str_contains($listenurl, $mount)) {
                    $chosen = $source;
                    break 2;
                }
            }
        }
        if ($chosen === null && !empty($sources)) {
            $chosen = $sources[0];
        }

        $listenurl = (string) ($chosen['listenurl'] ?? '');
        $mount = '';
        if ($listenurl !== '') {
            $path = parse_url($listenurl, PHP_URL_PATH);
            $mount = is_string($path) ? $path : '';
        }

        $results[] = [
            'station' => $name,
            'status' => ($mount === '/autodj' ? 'auto' : 'live'),
            'title' => (string) ($chosen['title'] ?? $chosen['x_icy_title'] ?? $chosen['server_name'] ?? 'Now Playing unavailable'),
            'listeners' => (int) ($icestats['listener_connections'] ?? $chosen['listeners'] ?? 0),
            'mount' => $mount,
        ];
    }

    @file_put_contents($cacheFile, json_encode($results, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
    return $results;
}
