from db.db import chore_schedules_db
from models.chore_schedule import ChoreSchedule
from tinydb import Query


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


def upsert_schedule(schedule: ChoreSchedule) -> None:
    q = Query()
    existing = chore_schedules_db.get((q.child_id == schedule.child_id) & (q.task_id == schedule.task_id))
    if existing:
        chore_schedules_db.update(schedule.to_dict(), (q.child_id == schedule.child_id) & (q.task_id == schedule.task_id))
    else:
        chore_schedules_db.insert(schedule.to_dict())


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


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


def delete_schedules_for_task(task_id: str) -> None:
    q = Query()
    chore_schedules_db.remove(q.task_id == task_id)
