"""交易监管专用会话(今日长会话,bot_mode=supervisor)."""
from __future__ import annotations

from typing import Any, Optional

from hub_ai.store import (
    CHAT_BOT_SUPERVISOR,
    append_chat_message,
    load_chat_store,
    save_chat_store,
)


def _supervisor_title(trading_day: str) -> str:
    return f"今日监管 {trading_day}"


def find_supervisor_session(trading_day: str) -> Optional[dict]:
    day = (trading_day or "").strip()[:10]
    store = load_chat_store()
    for s in store.get("sessions") or []:
        if str(s.get("bot_mode") or "") != CHAT_BOT_SUPERVISOR:
            continue
        if str(s.get("trading_day") or "") == day:
            return s
    return None


def ensure_supervisor_session(trading_day: str) -> dict:
    day = (trading_day or "").strip()[:10]
    existing = find_supervisor_session(day)
    if existing:
        return existing
    store = load_chat_store()
    from datetime import datetime
    import uuid

    session = {
        "id": uuid.uuid4().hex,
        "trading_day": day,
        "title": _supervisor_title(day),
        "bot_mode": CHAT_BOT_SUPERVISOR,
        "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "updated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "messages": [],
        "rolling_summary": "",
        "supervisor_locked": True,
    }
    store.setdefault("sessions", []).append(session)
    save_chat_store(store)
    return session


def append_supervisor_system_message(
    session_id: str,
    content: str,
    *,
    event_type: str = "",
    level: str = "info",
) -> dict:
    store = load_chat_store()
    target = None
    for s in store.get("sessions") or []:
        if str(s.get("id")) == str(session_id):
            target = s
            break
    if not target:
        raise KeyError("session_not_found")
    from datetime import datetime

    msg = {
        "role": "system",
        "content": (content or "").strip(),
        "at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "event_type": event_type,
        "level": level,
    }
    target.setdefault("messages", []).append(msg)
    target["updated_at"] = msg["at"]
    save_chat_store(store)
    return target


def append_supervisor_ai_message(session_id: str, content: str) -> dict:
    return append_chat_message(session_id, "assistant", content)


def get_supervisor_session_state(trading_day: str) -> dict[str, Any]:
    from hub_ai.client import model_label

    session = ensure_supervisor_session(trading_day)
    msgs = session.get("messages") or []
    unread = sum(1 for m in msgs if m.get("role") == "system" and not m.get("read"))
    return {
        "ok": True,
        "session": session,
        "trading_day": trading_day,
        "message_count": len(msgs),
        "unread_system": unread,
        "model": model_label(),
    }
