"""Контекст быстрого ответа: последняя активная заявка пользователя."""
from datetime import datetime, timedelta, timezone

from database.connection import get_db

_TTL_MINUTES = 60


async def set_reply_context(max_user_id: int, task_id: int, task_number: int | None) -> None:
    """Записать / обновить последнюю активную заявку пользователя."""
    db = get_db()
    await db.execute(
        """
        INSERT INTO user_reply_context (max_user_id, task_id, task_number, updated_at)
        VALUES (?, ?, ?, datetime('now'))
        ON CONFLICT(max_user_id) DO UPDATE SET
            task_id     = excluded.task_id,
            task_number = excluded.task_number,
            updated_at  = excluded.updated_at
        """,
        (max_user_id, task_id, task_number),
    )
    await db.commit()


async def get_reply_context(max_user_id: int) -> dict | None:
    """Вернуть контекст если он свежий (< TTL минут), иначе None."""
    db = get_db()
    async with db.execute(
        "SELECT task_id, task_number, updated_at FROM user_reply_context WHERE max_user_id = ?",
        (max_user_id,),
    ) as cur:
        row = await cur.fetchone()
    if not row:
        return None
    try:
        updated_at = datetime.fromisoformat(row["updated_at"]).replace(tzinfo=timezone.utc)
    except ValueError:
        return None
    if datetime.now(tz=timezone.utc) - updated_at > timedelta(minutes=_TTL_MINUTES):
        return None
    return dict(row)


async def clear_reply_context(max_user_id: int) -> None:
    db = get_db()
    await db.execute("DELETE FROM user_reply_context WHERE max_user_id = ?", (max_user_id,))
    await db.commit()
