"""Conversational continuity runtime."""

from __future__ import annotations

import time


ACTIVE_CONVERSATIONS: dict[int, dict] = {}


def touch_conversation(chat_id: int, user_id: int, text: str) -> None:
    ACTIVE_CONVERSATIONS[chat_id] = {
        "user_id": user_id,
        "last_text": text[:500],
        "updated_at": time.time(),
    }


def should_continue_conversation(chat_id: int, user_id: int, text: str) -> bool:
    convo = ACTIVE_CONVERSATIONS.get(chat_id)

    if not convo:
        return False

    if convo["user_id"] != user_id:
        return False

    if time.time() - convo["updated_at"] > 180:
        return False

    followups = (
        "خب",
        "بعدش",
        "یعنی چی",
        "چرا",
        "چطور",
        "عه",
        "جدی",
        "ادامه بده",
        "بیشتر بگو",
    )

    lowered = text.lower().strip()

    return any(lowered.startswith(item) for item in followups)


def conversation_context(chat_id: int) -> str:
    convo = ACTIVE_CONVERSATIONS.get(chat_id)

    if not convo:
        return ""

    return f"آخرین موضوع گفتگو: {convo['last_text']}"
