"""Test the correct channel ID for Sky Sport Uno."""
import urllib.request, json
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

rome = ZoneInfo("Europe/Rome")
now = datetime.now(rome)
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
end = today + timedelta(hours=28)

utc_start = today.astimezone(ZoneInfo("UTC")).strftime("%Y-%m-%dT%H:%M:%SZ")
utc_end = end.astimezone(ZoneInfo("UTC")).strftime("%Y-%m-%dT%H:%M:%SZ")


def test_channel(env, channel_num, label):
    url = (
        f"https://apid.sky.it/gtv/v1/events"
        f"?from={utc_start}&to={utc_end}"
        f"&pageSize=5&pageNum=0&env={env}&channels={channel_num}"
    )
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    try:
        resp = urllib.request.urlopen(req, timeout=15)
        data = json.loads(resp.read().decode("utf-8"))
        events = data.get("events", [])
        total = data.get("total", 0)
        if events:
            first_title = events[0].get("eventTitle", "?")
            print(f"  OK    {label} ({env}#{channel_num}): {total} eventi, primo: '{first_title}'")
        else:
            print(f"  VUOTO {label} ({env}#{channel_num}): 0 eventi")
    except Exception as ex:
        print(f"  ERRORE {label} ({env}#{channel_num}): {ex}")


print(f"Periodo: {utc_start} -> {utc_end}")
print()

print("=== SKY SPORT UNO ===")
test_channel("DTH", "11346", "id 11346 (config attuale - servicekey 2900)")
test_channel("DTH", "9097",  "id 9097  (servicekey 23)")
