"""Foreground council convene tool (Slice 1: manual trigger)."""

from __future__ import annotations

import json
import logging

from langchain_core.tools import tool
from pydantic import BaseModel, Field

_log = logging.getLogger(__name__)


def _origin_thread_id() -> str:
    try:
        from persistence import get_current_agent_thread_id

        return (get_current_agent_thread_id() or "").strip()
    except Exception:
        return ""


class ConveneCouncilInput(BaseModel):
    question_frame: str = Field(
        ...,
        description=(
            "Captain's framed question and constraints for the council pipeline. "
            "Include what to research, verify, and stress-test."
        ),
    )


@tool(args_schema=ConveneCouncilInput)
def convene_council(question_frame: str) -> str:
    """Convene the council pipeline (Researcher → Verifier → Contrarian) for this thread.

    After success, end the turn — do not answer the substantive question until synthesis delivery.
    """
    frame = (question_frame or "").strip()
    if not frame:
        return json.dumps({"ok": False, "error": "question_frame is required"})
    tid = _origin_thread_id()
    if not tid:
        return json.dumps({"ok": False, "error": "no active thread for council spawn"})

    try:
        from tool_policy import get_current_policy_context
        from utils.council_orchestrator import (
            COUNCIL_BATCH_ACTIVATED_MARKER,
            council_enabled,
            spawn_council_batch,
        )
        from utils.council_triggers import is_council_foreground_allowed

        ctx = get_current_policy_context()
        if not is_council_foreground_allowed(
            ctx,
            subagent_mode=bool(getattr(ctx, "subagent_mode", False) if ctx else False),
        ):
            return json.dumps(
                {
                    "ok": False,
                    "error": "convene_council is only available in foreground chat (not subagent/messaging/background).",
                }
            )

        if not council_enabled():
            return json.dumps(
                {
                    "ok": False,
                    "error": "Council mode is disabled (set [council] enabled=true and mode≠off).",
                }
            )
        result = spawn_council_batch(
            origin_thread_id=tid,
            council_frame=frame,
            allow_in_flight_turn=True,
        )
        bid = str(result.get("council_batch_id") or "")
        msg = str(result.get("message") or "")
        activation_persisted = False
        try:
            from utils.council_offers import deliver_council_spawn_activation

            activation_persisted = deliver_council_spawn_activation(tid, message=msg)
        except Exception:
            _log.warning("convene_council activation bubble failed", exc_info=True)
        try:
            from utils.council_offers import schedule_council_honest_stop_wake

            schedule_council_honest_stop_wake(tid)
        except Exception:
            _log.debug("convene_council honest-stop wake schedule failed", exc_info=True)
        payload = {
            "ok": True,
            "council_batch_id": bid,
            "researcher_task_id": result.get("researcher_task_id"),
            "verifier_task_id": result.get("verifier_task_id"),
            "contrarian_task_id": result.get("contrarian_task_id"),
            "message": msg,
            "honest_stop": True,
            "activation_persisted": activation_persisted,
            "instruction": (
                f"{COUNCIL_BATCH_ACTIVATED_MARKER} convened. "
                "Tell the operator council is running, then END this turn without answering the question."
            ),
        }
        return json.dumps(payload, ensure_ascii=False)
    except ValueError as exc:
        err = str(exc).strip() or "preflight refused"
        try:
            from utils.council_offers import deliver_council_spawn_refusal

            deliver_council_spawn_refusal(tid, reason=err)
        except Exception:
            _log.warning("convene_council refusal bubble failed", exc_info=True)
        return json.dumps({"ok": False, "error": err}, ensure_ascii=False)
    except Exception as exc:
        err = f"council spawn failed: {type(exc).__name__}: {exc}"
        _log.warning("convene_council failed", exc_info=True)
        try:
            from utils.council_offers import deliver_council_spawn_refusal

            deliver_council_spawn_refusal(tid, reason=err)
        except Exception:
            _log.warning("convene_council refusal bubble failed", exc_info=True)
        return json.dumps({"ok": False, "error": err}, ensure_ascii=False)
