"""
chat_logic.py — the UI-agnostic conversation layer for the PoC.

Streamlit/Flask are great for a fast demo, but UI code is hard to test. So we put
ALL the behavior here (testable, no browser) and let the UI files be thin shells.
This wraps the Lab 07 capstone Assistant and manages the human-approval handshake
that a transfer needs.
"""
from __future__ import annotations

import itertools
import os
import sys

# Make the Lab 07 capstone importable (it in turn wires labs 01/02/03/06).
_LABS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(_LABS, "lab-07-capstone"))
from assistant import Assistant   # noqa: E402

DEMO_USER = "user_amal"
DEMO_ACCOUNT = "AE070331234567890123456"


class ChatSession:
    """One user's conversation. `send()` returns a result dict; if a transfer is
    proposed it sets `awaiting_approval`, and the UI calls `approve()`."""

    def __init__(self, user: str = DEMO_USER, account_id: str = DEMO_ACCOUNT) -> None:
        self.assistant = Assistant()
        self.user, self.account = user, account_id
        self._turn = itertools.count(1)
        self.cid = "ui-session"
        self.pending_thread: str | None = None
        self.history: list[tuple[str, str]] = []   # (role, text) for the UI to render

    @property
    def awaiting_approval(self) -> bool:
        return self.pending_thread is not None

    def send(self, message: str) -> dict:
        if self.awaiting_approval:
            # Don't accept a new message while a transfer awaits a decision.
            return {"answer": "Please approve or decline the pending transfer first.",
                    "pending": True}
        thread = f"{self.cid}-{next(self._turn)}"
        r = self.assistant.chat(message, self.user, self.account, thread)
        self.history.append(("user", message))
        self.history.append(("assistant", r["answer"]))
        if r.get("pending"):
            self.pending_thread = thread
        return r

    def approve(self, approved: bool) -> dict | None:
        if not self.pending_thread:
            return None
        res = self.assistant.approve(self.pending_thread, approved, approver="ui_user")
        self.pending_thread = None
        self.history.append(("assistant", res["answer"]))
        return res
