import requests
from . import auth, user
from datetime import datetime

def get_schedule_week(login_method, *args, **kwargs):
    """get_student_info

    Args:
        login_method (string): How do you login? (access_token/refresh_token/uname_pword)
        Access_token:
            argh[0]: access_token
        refresh
            
        

    Returns:
        JSON: Student info.
    """
    
    try:
        match login_method:
            case "access_token": 
                access_token = args[0]
            case "refresh_token":                
                returned_rt = auth.using_refresh_token(args[0])
                access_token = returned_rt["access_token"]
            case "uname_pword":
                if len(args) > 3: email = args[3]
                else: email = None
                returned_up = auth.using_uname_pword(args[0], args[1], args[2], email)
                access_token = returned_up["access_token"]
            case _:
                return "This login method does not exist."
    except IndexError as e:
        return "Somewhere there is this error."
    
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Accept": "application/json",
        "Accept-Language": "en-US",
        "User-Agent": "Mozilla/5.0"
    }
        
    current_date = datetime.now()
    year, week_num, day_of_week = current_date.isocalendar()
    
    if "week" in kwargs: week_data = kwargs.get("week")
    else: week_data = str(week_num)
    
    student_id = user.get_student_uuid("access_token", access_token)
    
    getStudentSchedule = requests.get(url=f"https://api.somtoday.nl/rest/v1/afspraakitems/{student_id}/jaar/2026/week/{week_data}", headers=headers)
    
    return getStudentSchedule.json()

def get_schedule_formatted(login_method, *args, **kwargs):
    week = kwargs.get("week", None)

    if week is not None:
        schedule_unformatted = get_schedule_week(login_method, *args, week=week)
    else:
        schedule_unformatted = get_schedule_week(login_method, *args)

    schedule_formatted = {}

    for lesson in schedule_unformatted["items"]:
        dt = datetime.fromisoformat(lesson["beginDatumTijd"])
        day_name = dt.strftime("%A")

        formatted_lesson = {
            "lesuurr": lesson.get("beginLesuur"),
            "start": lesson.get("beginDatumTijd"),
            "einde": lesson.get("eindDatumTijd"),
            "locatie": lesson.get("locatie"),
            "omschrijving": lesson.get("omschrijving"),
            "vaknaam": lesson.get("vak", {}).get("naam"),
            "bijlagen": lesson.get("bijlagen", []),
            "docent": lesson.get("docentNamen", [])
        }

        if day_name not in schedule_formatted:
            schedule_formatted[day_name] = []

        schedule_formatted[day_name].append(formatted_lesson)

    for day in schedule_formatted:
        schedule_formatted[day].sort(key=lambda x: x["start"])

    return schedule_formatted

def get_schedule_today(login_method, *args, **kwargs):
    full_schedule = get_schedule_formatted(login_method, *args, **kwargs)

    today_name = datetime.now().strftime("%A")

    return full_schedule.get(today_name, [])