import urllib.request
import json

url = "https://libretto.mmcinet.eu/canti/api/v3/get_all_app_tables?uuid=pwa-cc-uuid&email=&platform=browser&version=1.0&gruppo=123456&all_song=false"
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
print("Fetching...")
with urllib.request.urlopen(req) as res:
    data = json.loads(res.read().decode("utf-8"))
    
    canti_pers = data.get("canti_personali", {}).get("data", [])
    states = {}
    for cp in canti_pers:
        state = cp.get("stato")
        states[state] = states.get(state, 0) + 1
        
    print("States found in canti_personali:")
    for state, count in states.items():
        print(f"- State {state}: {count} songs")
        
    # Let's also check if there are any duplicate IDs between canti and canti_personali
    canti_ids = {c["id_canti"] for c in data.get("canti", {}).get("data", [])}
    canti_pers_ids = {cp["id_canti"] for cp in canti_pers}
    intersection = canti_ids.intersection(canti_pers_ids)
    print(f"Number of duplicate song IDs between global catalog and canti_personali: {len(intersection)}")
    if len(intersection) > 0:
        print("First 5 duplicate IDs:")
        print(list(intersection)[:5])
        # Find one example of duplicate
        dup_id = list(intersection)[0]
        global_dup = next(c for c in data["canti"]["data"] if c["id_canti"] == dup_id)
        pers_dup = next(cp for cp in canti_pers if cp["id_canti"] == dup_id)
        print(f"\nExample Duplicate (ID {dup_id}):")
        print(f"Global: Title='{global_dup.get('titolo')}', Stato={global_dup.get('stato')}")
        print(f"Personal: Title='{pers_dup.get('titolo')}', Stato={pers_dup.get('stato')}")
