import re

def parse_m3u(m3u_text: str) -> list[dict]:
    """M3Uテキストをパースしてチャンネルリストを返す"""
    channels = []
    lines = m3u_text.strip().split('\n')
    i = 0
    while i < len(lines):
        line = lines[i].strip()
        if line.startswith('#EXTINF'):
            name = line.split(',', 1)[-1] if ',' in line else 'Unknown'
            group = re.search(r'group-title="([^"]*)"', line)
            tvg_id = re.search(r'tvg-id="([^"]*)"', line)
            url = lines[i + 1].strip() if i + 1 < len(lines) else ''
            channels.append({
                'name': name,
                'group': group.group(1) if group else '',
                'tvg_id': tvg_id.group(1) if tvg_id else '',
                'url': url
            })
            i += 1
        i += 1
    return channels

# 使用例
with open('combined-playlist.m3u', encoding='utf-8') as f:
    m3u_text = f.read()

channels = parse_m3u(m3u_text)
print(f'Total channels: {len(channels)}')

# グループ別集計
from collections import Counter
groups = Counter(ch['group'] for ch in channels)
for group, count in groups.most_common(10):
    print(f'  {group}: {count}ch')
