import urllib.request
import re

def list_channels(m3u_url: str, keyword: str = "") -> list[dict]:
    """M3U URL からチャンネル一覧を取得してフィルタリングする"""
    with urllib.request.urlopen(m3u_url, timeout=15) as resp:
        content = resp.read().decode("utf-8")

    channels = []
    lines = content.splitlines()
    for i, line in enumerate(lines):
        if not line.startswith("#EXTINF"):
            continue
        name = line.split(",", 1)[-1].strip()
        url = lines[i + 1].strip() if i + 1 < len(lines) else ""
        group = re.search(r'group-title="([^"]+)"', line)
        channels.append({
            "name": name,
            "url": url,
            "group": group.group(1) if group else "",
        })

    if keyword:
        channels = [c for c in channels if keyword in c["name"]]
    return channels

if __name__ == "__main__":
    M3U = "https://raw.githubusercontent.com/CCSH/IPTV/refs/heads/main/live_lite.m3u"
    results = list_channels(M3U, keyword="卫视")
    for ch in results[:10]:
        print(f"{ch['name']:20s}  [{ch['group']}]")
        print(f"  台標: https://raw.githubusercontent.com/CCSH/IPTV/refs/heads/main/logo/{ch['name']}.png")
