"""Active-profile resolution: a caregiver account can manage several patient
profiles, so every screen that used to assume `current_user.patient` (1:1)
now needs to know which profile is currently "active" in this browser session.
"""
from flask import session
from flask_login import current_user

from app.models import CaregiverLink


def get_managed_patient_ids() -> set:
    return {link.patient_id for link in current_user.caregiver_links}


def get_active_patient():
    """Returns the active Patient for the logged-in caregiver, or None if
    none is set/valid and there's more than one to choose from (caller should
    redirect to the profile picker in that case).
    """
    patients = current_user.patients
    if not patients:
        return None

    active_id = session.get("active_patient_id")
    if active_id:
        match = next((p for p in patients if p.id == active_id), None)
        if match:
            return match

    if len(patients) == 1:
        session["active_patient_id"] = patients[0].id
        return patients[0]

    return None


def set_active_patient(patient_id: int) -> bool:
    """Returns True and sets the session if current_user manages this patient."""
    if patient_id not in get_managed_patient_ids():
        return False
    session["active_patient_id"] = patient_id
    return True


def get_caregiver_link(patient_id: int):
    return CaregiverLink.query.filter_by(
        user_id=current_user.id, patient_id=patient_id
    ).first()
