import subprocess
from urllib.request import Request, urlopen

STREAM_URL = "https://s2.audiostream.hu/juventus_192k"
CHUNK_SIZE = 4096

def run():
    print("🎶 Console Web Radio Player")
    print("Press Ctrl+C to stop\n")

    player = subprocess.Popen(
        ["ffplay", "-nodisp", "-autoexit", "-loglevel", "quiet", "-"],
        stdin=subprocess.PIPE
    )

    req = Request(
        STREAM_URL,
        headers={
            "User-Agent": "PythonRadio/1.0",
            "Icy-MetaData": "1"
        }
    )

    try:
        with urlopen(req) as response:
            metaint = int(response.headers.get("icy-metaint", 0))
            bytes_until_meta = metaint

            while True:
                data = response.read(min(CHUNK_SIZE, bytes_until_meta))
                if not data:
                    break

                player.stdin.write(data)
                bytes_until_meta -= len(data)

                if bytes_until_meta == 0:
                    meta_len = response.read(1)
                    if not meta_len:
                        break

                    meta_size = meta_len[0] * 16
                    if meta_size > 0:
                        meta = response.read(meta_size)
                        _parse_metadata(meta)

                    bytes_until_meta = metaint

    except KeyboardInterrupt:
        print("\n🛑 Stopped")

    player.stdin.close()
    player.wait()

def _parse_metadata(raw):
    try:
        text = raw.rstrip(b"\0").decode("utf-8", errors="ignore")
        if "StreamTitle" in text:
            title = text.split("StreamTitle='")[1].split("';")[0]
            if title.strip():
                print(f"🎵 Now playing: {title}")
    except Exception:
        pass
