from tinydb import Query
from db.db import routine_schedules_db
from models.routine_schedule import RoutineSchedule


def get_schedule(child_id: str, routine_id: str) -> RoutineSchedule | None:
    q = Query()
    result = routine_schedules_db.search((q.child_id == child_id) & (q.routine_id == routine_id))
    if not result:
        return None
    return RoutineSchedule.from_dict(result[0])


def upsert_schedule(schedule: RoutineSchedule) -> None:
    q = Query()
    existing = routine_schedules_db.get((q.child_id == schedule.child_id) & (q.routine_id == schedule.routine_id))
    if existing:
        routine_schedules_db.update(
            schedule.to_dict(),
            (q.child_id == schedule.child_id) & (q.routine_id == schedule.routine_id)
        )
    else:
        routine_schedules_db.insert(schedule.to_dict())


def delete_schedule(child_id: str, routine_id: str) -> bool:
    q = Query()
    existing = routine_schedules_db.get((q.child_id == child_id) & (q.routine_id == routine_id))
    if not existing:
        return False
    routine_schedules_db.remove((q.child_id == child_id) & (q.routine_id == routine_id))
    return True


def delete_schedules_for_child(child_id: str) -> None:
    q = Query()
    routine_schedules_db.remove(q.child_id == child_id)


def delete_schedules_for_routine(routine_id: str) -> None:
    q = Query()
    routine_schedules_db.remove(q.routine_id == routine_id)
