from tinydb import Query
from db.db import routine_db
from models.routine import Routine


def add_routine(routine: Routine) -> None:
    routine_db.insert(routine.to_dict())


def get_routine(routine_id: str) -> Routine | None:
    q = Query()
    result = routine_db.search(q.id == routine_id)
    if not result:
        return None
    return Routine.from_dict(result[0])


def update_routine(routine: Routine) -> bool:
    q = Query()
    existing = routine_db.get(q.id == routine.id)
    if not existing:
        return False
    routine_db.update(routine.to_dict(), q.id == routine.id)
    return True


def delete_routine(routine_id: str) -> bool:
    q = Query()
    existing = routine_db.get(q.id == routine_id)
    if not existing:
        return False
    routine_db.remove(q.id == routine_id)
    return True


def list_routines_for_user(user_id: str) -> list[Routine]:
    q = Query()
    results = routine_db.search((q.user_id == user_id) | (q.user_id == None))
    return [Routine.from_dict(r) for r in results]
