# %%
from datetime import datetime, time, date

from competitions import get_teams_from_staffel
from schluesselzahlen import get_schluesselzahlen
from rahmentermine import get_rahmentermine
from spielstaetten import get_venues

# staffel = "Brandible Stadtliga B"
# teams = get_teams_from_staffel(staffel)
def datetime_serializer(obj):
    if isinstance(obj, datetime) or isinstance(obj, date) or isinstance(obj, time):
        return obj.isoformat()  # or use obj.strftime("%Y-%m-%d %H:%M:%S")
    raise TypeError("Type not serializable")

staffeln_raw, teams = get_teams_from_staffel()


staffeln = []
divisions = []
court_names = []
venues = []

for s in staffeln_raw:
    if len(teams[s]) < 4 or len(teams[s]) % 2 == 1:
        # if len(teams[s]) > 0:
        #     print(s, teams[s][0]['MS_ART'], len(teams[s]))
        # else:
        #     print(s, "no teams")
        print("Incompatible", s)
        continue
        
    nTeams = len(teams[s])
    pattern, opponent = get_schluesselzahlen(nTeams)
    
    ms_art = teams[s][0]['MS_ART']
    if ms_art in ["A-Junioren","B-Junioren","C-Junioren","D-Junioren","D-Juniorinnen"]:
        ms_art = "Junioren A-D"
    elif ms_art in ["Herren Ü50"]:
        ms_art = "Senioren Ü50"
    elif ms_art in ["Herren Ü35"]:
        ms_art = "Senioren Ü35"
    
    rahmentermine = get_rahmentermine(ms_art, nTeams)

    if not rahmentermine:
        print("No rahmentermine for", s, ms_art, nTeams)
        continue
    divisions.append({
        "name": s,
        "teams": teams[s],
        "nTeams": nTeams,
        "ms_art": ms_art,   
        "pattern": pattern,
        "opponent": opponent,
        "rahmentermine": rahmentermine
    })
    # for t in teams[s]:
    #     if not t['SPIELSTAETTE'] in court_names:
    #         courts += [{"name":t['SPIELSTAETTE']}]
    #         court_names += [t['SPIELSTAETTE']]

venues = get_venues()


""" dump json """
import json
with open("data/competitions.json", "w", encoding="utf-8") as f:
    json.dump({'divisions':divisions,'venues':venues}, f, default=datetime_serializer, ensure_ascii=False, indent=4)
# %%
