"""Bounded per-conversation state for explicit direct-command continuation.

The store only keeps the minimal routing metadata required to resume a direct
command with explicit c_id-isolated state: it never retains responses, tool
output, or raw conversation IDs. The single exception is ``task_digest`` —
a bounded (600-char) slice of the command's own argument text, kept so the
ordinary-chat path can bridge task context when a later followup skips the
exact continuation phrasing. Entries are isolated by a hash of ``c_id``,
expire automatically, and are capacity bounded.
"""

from __future__ import annotations

import hashlib
import re
import threading
import time
from collections import OrderedDict
from dataclasses import dataclass, replace

from lts_logger import lts_logger


_CONTINUATION_RE = re.compile(
    r"^(?:请)?(?:(?:继续|接着|恢复)(?:回复|执行|处理|完成|做|走下去)?|(?:确认|确定)(?:执行|续跑)?|续跑|continue|resume)"
    r"(?:(?:上次|刚才|你|您)(?:的)?)?(?:原任务|现任务|任务|工作)?"
    r"(?:[,,]?并在完成后给出最终结果)?(?:吧|呀|啊)?[,,。!!]*$",
    re.IGNORECASE,
)

# 评测/客户端把原任务摘要放在中文引号中,例如:
# "继续完成原任务「……」尚未交付的部分。"。这不是普通追问,必须与裸"继续"走同一条续接路由。
_DESCRIBED_CONTINUATION_RE = re.compile(
    r"^(?:请)?继续(?:完成|推进)(?:原任务|现任务)[「“\"](?s:.+?)[」”\"].*$"
)


_TASK_DIGEST_MAX_CHARS = 600
_TASK_CONTEXT_TTL_SECONDS = 3600.0

# 只清理长时间没有执行进度的遗留会话;不是命令执行时长上限。
_DEFAULT_IN_FLIGHT_STALE_SECONDS = 7200.0
_IN_FLIGHT_STALE_GRACE_SECONDS = 60.0


def _in_flight_stale_seconds(command_name: str = "") -> float:
    """Release an orphaned ownership record after prolonged inactivity."""
    try:
        from app.config import settings

        command_cap = float(
            getattr(settings, "chat_stream_command_max_seconds", 0.0) or 0.0,
        )
        workflow_cap = (
            float(max(
                settings.workflow_mcp_tool_timeout_seconds,
                settings.workflow_claude_skill_timeout_seconds,
            ))
            if command_name == "workflow" else 0.0
        )
    except (ImportError, TypeError, ValueError):
        command_cap = 0.0
        workflow_cap = 0.0
    return max(_DEFAULT_IN_FLIGHT_STALE_SECONDS, command_cap, workflow_cap) + _IN_FLIGHT_STALE_GRACE_SECONDS


def _conversation_key(c_id: str | None) -> str | None:
    """Return a fixed-size, non-plaintext key for one conversation ID."""
    if not c_id:
        return None
    return hashlib.sha256(str(c_id).encode("utf-8", errors="replace")).hexdigest()


def is_direct_command_continuation(text: str) -> bool:
    """Return true only for an explicit, standalone continuation request."""
    normalized = re.sub(r"\s+", "", str(text or "").strip())
    return bool(normalized and _CONTINUATION_RE.fullmatch(normalized))


def is_continuation_request(text: str) -> bool:
    """Return true for standalone or described explicit continuation text.

    The strict predicate remains public for callers that only accept a control
    word. Routing callers should use this broader predicate so scoring, chat,
    and dashboard ownership agree on long simulated-user continuation wording.
    """
    normalized = re.sub(r"\s+", "", str(text or "").strip())
    return bool(
        normalized
        and (
            _CONTINUATION_RE.fullmatch(normalized)
            or _DESCRIBED_CONTINUATION_RE.fullmatch(normalized)
        )
    )


def confirmation_reply(text: str) -> str | None:
    """Recognize standalone decisions; callers must require a pending dialog."""
    normalized = str(text or "").strip()
    if re.fullmatch(r"(?:请)?(?:确认|确定)(?:执行|继续|续跑)?[。!!,,\s]*", normalized) or re.fullmatch(
        r"confirm(?:ed)?[.!\s]*", normalized, re.IGNORECASE,
    ):
        return "confirmed"
    if re.fullmatch(r"(?:请)?(?:取消|拒绝|不要执行|不执行)[。!!,,\s]*", normalized) or re.fullmatch(
        r"reject(?:ed)?[.!\s]*", normalized, re.IGNORECASE,
    ):
        return "rejected"
    return None


def continuation_action_label(
    text: str, *, confirmation: str | None = None, workflow: bool = False,
) -> str:
    """给已确认归属原任务的控制输入提供一致的展示语义。"""
    if confirmation == "confirmed":
        return "确认后执行"
    if confirmation == "rejected":
        return "否决后重议"
    normalized = str(text or "").strip()
    if workflow:
        if normalized.casefold() == "approve":
            return "确认后执行"
        if re.match(r"^reject(?:$|[\s::])", normalized, re.IGNORECASE):
            return "否决后重议"
    decision = confirmation_reply(normalized)
    if decision:
        return "确认后执行" if decision == "confirmed" else "否决后重议"
    return "继续处理" if is_continuation_request(normalized) else ""


@dataclass(frozen=True)
class DirectCommandSession:
    c_id: str
    command_name: str
    skill_name: str
    session_id: str | None
    generation: int
    in_flight: bool
    updated_at: float
    task_digest: str = ""
    workflow_id: str | None = None
    # 总耗时始终从开始时刻计算;续接请求不能刷新执行租约。
    started_at: float = 0.0
    # 仅正在执行的进度续租,防止长任务被当作遗留条目释放。
    execution_activity_at: float = 0.0


class DirectCommandSessionStore:
    """Thread-safe TTL/LRU store keyed by one conversation ID."""

    def __init__(self, *, ttl_seconds: float | None = None, max_entries: int = 256) -> None:
        if ttl_seconds is None:
            from app.config import settings

            ttl_seconds = settings.direct_command_resume_ttl_seconds
        self._ttl_seconds = max(1.0, float(ttl_seconds))
        self._max_entries = max(1, int(max_entries))
        self._items: OrderedDict[str, DirectCommandSession] = OrderedDict()
        self._lock = threading.RLock()
        self._next_generation = 0
        self._next_stale_generation = 0

    def _prune_locked(self, now: float) -> None:
        # 清理未执行时释放超时会话,并使旧代调用失效
        stale = [
            c_id
            for c_id, item in self._items.items()
            if item.in_flight and now - item.execution_activity_at > _in_flight_stale_seconds(item.command_name)
        ]
        stale_events: list[tuple[int, str]] = []
        for c_id in stale:
            item = self._items[c_id]
            self._next_stale_generation -= 1
            self._items[c_id] = replace(
                item,
                in_flight=False,
                generation=self._next_stale_generation,
                session_id=None,
                workflow_id=None,
                updated_at=now,
            )
            stale_events.append(
                (int(now - item.started_at), item.command_name),
            )
        expired = [
            c_id
            for c_id, item in self._items.items()
            if not item.in_flight and now - item.updated_at > self._ttl_seconds
        ]
        for c_id in expired:
            self._items.pop(c_id, None)
        for elapsed, command_name in stale_events:
            lts_logger.log(
                "direct_command_in_flight_stale_released",
                elapsed_seconds=elapsed,
                command_name=command_name,
            )

    def _make_room_locked(self) -> bool:
        """Evict only idle sessions; active commands always fail closed."""
        if len(self._items) < self._max_entries:
            return True
        for key, item in self._items.items():
            if not item.in_flight:
                self._items.pop(key, None)
                return True
        return False

    def begin(
        self,
        c_id: str | None,
        command_name: str,
        skill_name: str,
        task_digest: str = "",
    ) -> DirectCommandSession | None:
        """Start a fresh command unless the conversation is already executing."""
        key = _conversation_key(c_id)
        if key is None:
            return None
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            current = self._items.get(key)
            if current is not None and current.in_flight:
                return None
            if current is None and not self._make_room_locked():
                return None
            self._next_generation += 1
            item = DirectCommandSession(
                c_id=key,
                command_name=command_name,
                skill_name=skill_name,
                session_id=None,
                workflow_id=None,
                generation=self._next_generation,
                in_flight=True,
                updated_at=now,
                task_digest=str(task_digest or "")[:_TASK_DIGEST_MAX_CHARS],
                started_at=now,
                execution_activity_at=now,
            )
            self._items[key] = item
            self._items.move_to_end(key)
            return item

    def update_session_id(
        self,
        c_id: str | None,
        command_name: str,
        generation: int,
        session_id: str | None,
    ) -> None:
        """Attach an SDK session only if the exact invocation is still current."""
        key = _conversation_key(c_id)
        if key is None or not session_id:
            return
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            if (
                item is None
                or item.command_name != command_name
                or item.generation != generation
            ):
                return
            self._items[key] = replace(
                item,
                session_id=str(session_id),
                updated_at=now,
            )
            self._items.move_to_end(key)

    def update_workflow_id(
        self,
        c_id: str | None,
        generation: int,
        workflow_id: str | None,
    ) -> None:
        """Bind a workflow checkpoint to the invocation that created its plan."""
        key = _conversation_key(c_id)
        if key is None or not workflow_id:
            return
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            if (
                item is None
                or item.command_name != "workflow"
                or item.generation != generation
                or not item.in_flight
            ):
                return
            self._items[key] = replace(
                item, workflow_id=str(workflow_id), updated_at=now,
            )
            self._items.move_to_end(key)

    def refresh_execution(
        self, c_id: str | None, command_name: str, generation: int,
    ) -> None:
        """Keep a live command owned while its own execution emits progress."""
        key = _conversation_key(c_id)
        if key is None:
            return
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            if (
                item is None or item.command_name != command_name
                or item.generation != generation or not item.in_flight
            ):
                return
            self._items[key] = replace(item, execution_activity_at=now)
            self._items.move_to_end(key)

    def get_for_continuation(
        self,
        c_id: str | None,
        text: str,
    ) -> DirectCommandSession | None:
        """Resolve an explicit continuation without consuming the session."""
        key = _conversation_key(c_id)
        if key is None or not is_continuation_request(text):
            return None
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            if item is None:
                return None
            self._items[key] = replace(item, updated_at=now)
            self._items.move_to_end(key)
            return self._items[key]

    def get_command_name(self, c_id: str | None) -> str | None:
        """Return the current direct-command route without duplicating state."""
        key = _conversation_key(c_id)
        if key is None:
            return None
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            return item.command_name if item is not None else None

    def get_recent_task_context(self, c_id: str | None) -> tuple[str, str] | None:
        """Return ``(command_name, task_digest)`` of a recent idle command session.

        Lets the ordinary-chat path bridge task context when a followup skips
        the exact continuation phrasing; returns None once the entry expired
        or was cleared after an explicit topic change.
        """
        key = _conversation_key(c_id)
        if key is None:
            return None
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            # 自释条目(负代):原任务可能仍在跑,摘要不桥接,防诱导重复执行
            if (
                item is None
                or item.in_flight
                or item.generation < 0
                or not item.task_digest
                or now - item.updated_at > _TASK_CONTEXT_TTL_SECONDS
            ):
                return None
            self._items[key] = replace(item, updated_at=now)
            self._items.move_to_end(key)
            return item.command_name, item.task_digest

    def claim_for_continuation(
        self,
        c_id: str | None,
        text: str,
        command_name: str,
    ) -> DirectCommandSession | None:
        """Atomically reserve one stored SDK session for a continuation turn.

        A single conversation/session may only have one in-flight invocation.
        This prevents duplicate "继续" requests from concurrently resuming the
        same Claude SDK session and potentially executing tools twice.
        """
        key = _conversation_key(c_id)
        if key is None or not is_continuation_request(text):
            return None
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            if (
                item is None
                or item.command_name != command_name
                or item.in_flight
            ):
                return None
            claimed = replace(
                item, in_flight=True, updated_at=now, started_at=now,
            )
            self._items[key] = claimed
            self._items.move_to_end(key)
            return claimed

    def release(
        self,
        c_id: str | None,
        command_name: str,
        generation: int,
    ) -> None:
        """Release only the invocation that owns the current generation."""
        key = _conversation_key(c_id)
        if key is None:
            return
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            if (
                item is None
                or item.command_name != command_name
                or item.generation != generation
            ):
                return
            self._items[key] = replace(item, in_flight=False, updated_at=now)
            self._items.move_to_end(key)

    def is_in_flight(self, c_id: str | None) -> bool:
        """Return whether the conversation currently owns an active command."""
        key = _conversation_key(c_id)
        if key is None:
            return False
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            return bool(item and item.in_flight)

    def in_flight_elapsed_seconds(self, c_id: str | None) -> int | None:
        """Active command 运行秒数;非 in-flight 返回 None(busy 文案数据源)。"""
        key = _conversation_key(c_id)
        if key is None:
            return None
        now = time.monotonic()
        with self._lock:
            self._prune_locked(now)
            item = self._items.get(key)
            if not item or not item.in_flight:
                return None
            # 用 started_at:updated_at 会被续接请求刷新,读数会归零失真
            return max(0, int(now - item.started_at))

    def clear_if_idle(self, c_id: str | None) -> bool:
        """Clear stale continuation state without deleting an active owner."""
        key = _conversation_key(c_id)
        if key is None:
            return False
        with self._lock:
            item = self._items.get(key)
            if item is not None and item.in_flight:
                return False
            return self._items.pop(key, None) is not None

    def forget_deleted_workflow(self, workflow_id: str) -> None:
        """删除历史图时清理其闲置续跑入口;执行中的所有权保持到收尾。"""
        with self._lock:
            for key, item in list(self._items.items()):
                if item.workflow_id == workflow_id and not item.in_flight:
                    self._items.pop(key, None)

    def clear(self, c_id: str | None) -> bool:
        """Backward-compatible safe clear; active sessions are preserved."""
        return self.clear_if_idle(c_id)

    def clear_all(self) -> None:
        """Test/support hook; production cleanup normally relies on TTL/LRU."""
        with self._lock:
            self._items.clear()


direct_command_sessions = DirectCommandSessionStore()