from tinydb import Query
from db.db import routine_items_db
from models.routine_item import RoutineItem


def add_item(item: RoutineItem) -> None:
    routine_items_db.insert(item.to_dict())


def get_item(item_id: str) -> RoutineItem | None:
    q = Query()
    result = routine_items_db.search(q.id == item_id)
    if not result:
        return None
    return RoutineItem.from_dict(result[0])


def get_items_for_routine(routine_id: str) -> list[RoutineItem]:
    q = Query()
    results = routine_items_db.search(q.routine_id == routine_id)
    items = [RoutineItem.from_dict(r) for r in results]
    return sorted(items, key=lambda i: (i.order, i.created_at))


def update_item(item: RoutineItem) -> bool:
    q = Query()
    existing = routine_items_db.get(q.id == item.id)
    if not existing:
        return False
    routine_items_db.update(item.to_dict(), q.id == item.id)
    return True


def delete_item(item_id: str) -> bool:
    q = Query()
    existing = routine_items_db.get(q.id == item_id)
    if not existing:
        return False
    routine_items_db.remove(q.id == item_id)
    return True


def delete_for_routine(routine_id: str) -> None:
    q = Query()
    routine_items_db.remove(q.routine_id == routine_id)
