from tinydb import Query
from db.db import routine_extensions_db
from models.routine_extension import RoutineExtension


def get_extension(child_id: str, routine_id: str, date: str) -> RoutineExtension | None:
    q = Query()
    result = routine_extensions_db.search(
        (q.child_id == child_id) & (q.routine_id == routine_id) & (q.date == date)
    )
    if not result:
        return None
    return RoutineExtension.from_dict(result[0])


def add_extension(extension: RoutineExtension) -> None:
    routine_extensions_db.insert(extension.to_dict())


def delete_extensions_for_child(child_id: str) -> None:
    q = Query()
    routine_extensions_db.remove(q.child_id == child_id)


def delete_extensions_for_routine(routine_id: str) -> None:
    q = Query()
    routine_extensions_db.remove(q.routine_id == routine_id)


def delete_extension_for_child_routine(child_id: str, routine_id: str) -> None:
    q = Query()
    routine_extensions_db.remove((q.child_id == child_id) & (q.routine_id == routine_id))


def get_extension_for_child_routine(child_id: str, routine_id: str) -> RoutineExtension | None:
    q = Query()
    results = routine_extensions_db.search((q.child_id == child_id) & (q.routine_id == routine_id))
    if not results:
        return None
    latest = max(results, key=lambda r: r.get('date', ''))
    return RoutineExtension.from_dict(latest)
