from db.db import task_extensions_db
from models.task_extension import TaskExtension
from tinydb import Query


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


def add_extension(extension: TaskExtension) -> None:
    task_extensions_db.insert(extension.to_dict())


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


def delete_extensions_for_task(task_id: str) -> None:
    q = Query()
    task_extensions_db.remove(q.task_id == task_id)


def delete_extension_for_child_task(child_id: str, task_id: str) -> None:
    q = Query()
    task_extensions_db.remove((q.child_id == child_id) & (q.task_id == task_id))


def get_extension_for_child_task(child_id: str, task_id: str) -> TaskExtension | None:
    """Return the extension for a child+task without filtering by date.

    Avoids timezone mismatches between the server (UTC) and the client's local
    date. The caller (or the frontend) is responsible for deciding whether the
    returned extension_date is still applicable.
    """
    q = Query()
    results = task_extensions_db.search(
        (q.child_id == child_id) & (q.task_id == task_id)
    )
    if not results:
        return None
    latest = max(results, key=lambda r: r.get('date', ''))
    return TaskExtension.from_dict(latest)
