#!/usr/bin/env python3

import re
import time
from pathlib import Path

PLAYLIST = Path("/srv/iptv/channels.m3u")
LOGFILE = Path("/srv/iptv/cache-icons.txt")

logo_re = re.compile(r'tvg-logo="([^"]+)"')

def get_total():
    urls = set()

    for line in PLAYLIST.read_text(
        encoding="utf-8",
        errors="replace"
    ).splitlines():

        if not line.startswith("#EXTINF"):
            continue

        m = logo_re.search(line)

        if m:
            urls.add(m.group(1).strip())

    return len(urls)


def get_progress():
    processed = set()

    success = 0
    failed = 0
    rate_limited = 0
    cache_hits = 0

    if not LOGFILE.exists():
        return 0, 0, 0, 0, 0

    with LOGFILE.open(
        "r",
        encoding="utf-8",
        errors="replace"
    ) as f:

        for line in f:

            if line.startswith("PROCESSING:"):
                url = line.split(":", 1)[1].strip()
                processed.add(url)

            elif line.startswith("SUCCESS:"):
                success += 1

            elif "FAILED" in line:
                failed += 1

            elif "429" in line or "RATE LIMITED" in line:
                rate_limited += 1

            elif "CACHE HIT:" in line:
                cache_hits += 1

    return (
        len(processed),
        success,
        failed,
        rate_limited,
        cache_hits
    )


total = get_total()

while True:

    done, success, failed, limited, hits = get_progress()

    percent = (done / total * 100) if total else 0
    remaining = max(total - done, 0)

    print("\033[2J\033[H", end="")

    print("IPTV Logo Cache Progress")
    print("========================")
    print()
    print(f"Total unique logos : {total:,}")
    print(f"Processed          : {done:,}")
    print(f"Remaining          : {remaining:,}")
    print(f"Progress           : {percent:6.2f}%")
    print()
    print(f"Successful         : {success:,}")
    print(f"Cache hits         : {hits:,}")
    print(f"Failed             : {failed:,}")
    print(f"Rate limited       : {limited:,}")
    print()
    print("Press Ctrl+C to exit monitor.")
    print("Downloader is NOT modified.")

    time.sleep(10)
