import json
from pathlib import Path

INPUT = Path("/var/www/html/IMBD/streamimdb-top.m3u")
OUTPUT = Path("/var/www/html/IMBD/streamimdb-auto.json")

lines = INPUT.read_text(encoding="utf-8", errors="ignore").splitlines()
items = []

for i, line in enumerate(lines):
    line = line.strip()
    if not line.startswith("#EXTINF"):
        continue

    name = line.split(",", 1)[-1].strip()
    image = ""

    if 'tvg-logo="' in line:
        image = line.split('tvg-logo="', 1)[1].split('"', 1)[0]

    link = ""
    for j in range(i + 1, len(lines)):
        nxt = lines[j].strip()
        if nxt and not nxt.startswith("#"):
            link = nxt
            break

    if name and link:
        items.append({
            "name": name,
            "image": image,
            "link": link
        })

OUTPUT.write_text(json.dumps(items, ensure_ascii=False, indent=2), encoding="utf-8")
print("Saved:", OUTPUT)
print("Movies:", len(items))