"""Brief — the signal output. Shows the system's strategic reasoning."""

from dataclasses import dataclass, field

from xyglue.thinking.models import ThinkingResult
from xyglue.config import EngineConfig


@dataclass
class Brief:
    mode: str = "semi"
    agent_names: dict[str, str] = field(default_factory=dict)
    benchmark_summary: str = ""
    habits_found: int = 0
    physics_found: int = 0
    recommended_path: str = "A"
    recommended_description: str = ""
    path_summaries: dict[str, str] = field(default_factory=dict)
    execution_status: str = ""
    path_used: str = ""
    was_healed: bool = False
    paths_attempted: list[str] = field(default_factory=list)
    template_status: str = ""

    def format_semi(self) -> str:
        scout = self.agent_names.get("scout", "Scout")
        physicist = self.agent_names.get("physicist", "Physicist")
        architect = self.agent_names.get("architect", "Architect")
        lines = [
            f"\U0001f50d {scout} mapped benchmark: {self.benchmark_summary}",
            f"   {physicist} classified {self.habits_found} habits, {self.physics_found} physics.",
            "",
            f"\u26a1 {architect} recommends Path {self.recommended_path}: {self.recommended_description}",
        ]
        for pid, summary in self.path_summaries.items():
            if pid != self.recommended_path:
                lines.append(f"   Path {pid}: {summary}")
        lines.extend(
            ["", "   [Execute Recommended]  [Show All Paths]  [Modify]  [Skip to C]"]
        )
        return "\n".join(lines)

    def format_auto(self) -> str:
        lines: list[str] = []
        if self.execution_status == "success":
            lines.append(f"\u2705 Complete. Path {self.path_used} succeeded.")
        else:
            lines.append(
                f"\u274c Failed. Attempted: {', '.join(self.paths_attempted)}"
            )
        scout = self.agent_names.get("scout", "Scout")
        lines.append(f"\U0001f50d {scout} benchmark: {self.benchmark_summary}")
        lines.append(
            f"   {self.habits_found} habits broken. {self.physics_found} physics respected."
        )
        if self.was_healed:
            lines.append("   \U0001f527 Self-healing activated.")
        status_map = {
            "promoted": "\U0001f4da Template promoted (proven).",
            "validating": "\U0001f4cb Template candidate submitted.",
            "rejected": "\U0001f4cb Below threshold.",
            "reset": "\U0001f4cb Validation reset.",
        }
        if self.template_status in status_map:
            lines.append(f"   {status_map[self.template_status]}")
        return "\n".join(lines)

    def format_fallthrough(
        self, from_path: str, to_path: str, reason: str
    ) -> str:
        return (
            f"\U0001f4ca Path {from_path} failed: {reason}\n"
            f"   Adapting Path {to_path}.\n"
            f"\u26a1 Executing Path {to_path}"
        )

    def format(self) -> str:
        return self.format_semi() if self.mode == "semi" else self.format_auto()


def build_brief(thinking_result: ThinkingResult, config: EngineConfig) -> Brief:
    benchmark = thinking_result.benchmark_map
    classified = thinking_result.classified_map
    recommended = thinking_result.get_path(thinking_result.recommended_path)
    tools_str = ", ".join(benchmark.standard_tools[:3])
    path_summaries: dict[str, str] = {}
    for path in thinking_result.paths:
        broken = len(path.habits_broken)
        path_summaries[path.id] = (
            f"{path.label} \u2014 {path.description} ({broken} habits broken)"
        )
    return Brief(
        mode=config.mode,
        agent_names=config.agent_names,
        benchmark_summary=f"{benchmark.domain}. Standard: {tools_str}.",
        habits_found=classified.habit_count,
        physics_found=classified.physics_count,
        recommended_path=thinking_result.recommended_path,
        recommended_description=recommended.description if recommended else "",
        path_summaries=path_summaries,
    )
