from __future__ import annotations

import re
from typing import Literal

from core.config import get_mesh_config, get_subagent_config, get_utility_config

MAX_TASK_TEXT_CHARS = 1600
MAX_CONTEXT_CHARS = 1600
MAX_OUTPUT_CHARS = 2600
MAX_BLACKBOARD_CHARS = 1800
MAX_ENVELOPE_CHARS = 1200

_FAIL_RE = re.compile(r"^FAIL\s*:\s*(.+)$", re.IGNORECASE)


def _trim(text: str, limit: int) -> str:
    raw = (text or "").strip()
    if len(raw) > limit:
        return raw[:limit] + "\n[truncated]"
    return raw


def _critic_enabled(kind: Literal["delegation", "mesh_task"]) -> bool:
    if kind == "delegation":
        return bool(get_subagent_config().get("handoff_critic_enabled", False))
    return bool(get_mesh_config().get("handoff_critic_enabled", False))


def maybe_critique_handoff(
    *,
    kind: Literal["delegation", "mesh_task"],
    task_text: str,
    context_text: str,
    output_text: str,
    blackboard_excerpt: str = "",
    envelope_summary: str = "",
) -> tuple[str, str | None]:
    """Return output unchanged unless a critic warning is generated."""
    if not _critic_enabled(kind):
        return output_text, None
    if not bool(get_utility_config().get("enabled", False)):
        return output_text, None

    prompt = (
        "You are a strict handoff critic.\n"
        "Return exactly one line.\n"
        "- PASS\n"
        "- FAIL: <short reason>\n"
        "Only emit FAIL when there is a clear contradiction or missing core step.\n\n"
        f"kind: {kind}\n\n"
        f"task:\n{_trim(task_text, MAX_TASK_TEXT_CHARS)}\n\n"
        f"context:\n{_trim(context_text, MAX_CONTEXT_CHARS)}\n\n"
        f"blackboard:\n{_trim(blackboard_excerpt, MAX_BLACKBOARD_CHARS)}\n\n"
        f"envelope:\n{_trim(envelope_summary, MAX_ENVELOPE_CHARS)}\n\n"
        f"output:\n{_trim(output_text, MAX_OUTPUT_CHARS)}"
    )

    try:
        from utility_model import utility_complete

        result = utility_complete(
            [{"role": "user", "content": prompt}],
            max_tokens=80,
            temperature=0.0,
            activity_operation="handoff_critic",
        )
    except Exception:
        return output_text, None
    if not result:
        return output_text, None

    first = (result or "").strip().splitlines()[0].strip()
    if first.upper() == "PASS":
        return output_text, None

    m = _FAIL_RE.match(first)
    if not m:
        return output_text, None
    reason = m.group(1).strip()[:240] or "Logical inconsistency detected."
    warning = f"[Handoff review] {reason}"
    return f"{warning}\n\n{output_text}".strip(), warning

