"""The Architect — generates three execution paths ranked by divergence.
PCT Components 09-10: The Break, Three Paths."""

import json
from typing import Any

from xyglue.thinking.models import ClassifiedMap, Path
from xyglue.config import EngineConfig


class Architect:
    """Designs Path A (max divergence), Path B (informed hybrid), Path C (optimized benchmark)."""

    DIVERGENCE_MULTIPLIERS = {
        "low": {"A": 0.4, "B": 0.2, "C": 0.1},
        "medium": {"A": 0.8, "B": 0.5, "C": 0.2},
        "high": {"A": 1.0, "B": 0.7, "C": 0.3},
    }

    def __init__(
        self,
        name: str = "Architect",
        ai_client: Any = None,
        model: str = "claude-sonnet-4-20250514",
    ) -> None:
        self.name = name
        self.ai_client = ai_client
        self.model = model

    async def design(
        self,
        classified_map: ClassifiedMap,
        available_tools: list[str],
        config: EngineConfig | None = None,
    ) -> list[Path]:
        divergence = config.divergence if config else "medium"
        if self.ai_client is None:
            return self._rule_based_design(
                classified_map, available_tools, divergence
            )

        multipliers = self.DIVERGENCE_MULTIPLIERS[divergence]
        habits = [c.to_dict() for c in classified_map.get_habits()]
        physics = [c.to_dict() for c in classified_map.get_physics()]
        cross_domain = classified_map.benchmark.cross_domain_components

        prompt = f"""You are {self.name}, a path generation agent.

Design THREE execution paths ranked by divergence from the benchmark.

GOAL: {classified_map.benchmark.goal_text}
DOMAIN: {classified_map.benchmark.domain}
TOOLS: {', '.join(available_tools)}
PHYSICS (cannot break): {json.dumps(physics, indent=2)}
HABITS (CAN break): {json.dumps(habits, indent=2)}
CROSS-DOMAIN AVAILABLE: {json.dumps(cross_domain)}
DIVERGENCE: {divergence}

Respond with JSON:
{{"paths": [
  {{"id": "A", "label": "Maximum Divergence", "description": "...",
    "divergence_level": {multipliers['A']},
    "habits_broken": [], "physics_respected": [], "cross_domain_imports": [],
    "steps": [{{"number": 1, "action": "...", "tool": "...", "params": {{}},
      "description": "...", "checkpoint": true/false, "idempotent": true/false, "timeout_ms": 30000}}],
    "tools_required": [], "risk_level": "high", "confidence": 0.0-1.0}},
  {{"id": "B", "label": "Informed Hybrid", ...}},
  {{"id": "C", "label": "Optimized Benchmark", ...}}
]}}

PATH A: Replace every habit. Pull cross-domain. The outlier approach.
PATH B: Keep physics, break habits selectively. Pragmatic outlier.
PATH C: Conventional enhanced. The floor — above average guaranteed.

Respond ONLY with JSON."""

        response = await self.ai_client.messages.create(
            model=self.model,
            max_tokens=4096,
            messages=[{"role": "user", "content": prompt}],
        )
        return self._parse_response(
            response.content[0].text, classified_map, divergence
        )

    def _parse_response(
        self, response: str, classified_map: ClassifiedMap, divergence: str
    ) -> list[Path]:
        try:
            text = response.strip()
            for prefix in ["```json", "```"]:
                if text.startswith(prefix):
                    text = text[len(prefix) :]
            if text.endswith("```"):
                text = text[:-3]
            data = json.loads(text.strip())
            paths = [Path.from_dict(p) for p in data.get("paths", [])]
            if len(paths) < 3:
                paths.extend(
                    self._rule_based_design(classified_map, [], divergence)[
                        len(paths) :
                    ]
                )
            return paths[:3]
        except (json.JSONDecodeError, KeyError):
            return self._rule_based_design(classified_map, [], divergence)

    def _rule_based_design(
        self,
        classified_map: ClassifiedMap,
        available_tools: list[str],
        divergence: str,
    ) -> list[Path]:
        multipliers = self.DIVERGENCE_MULTIPLIERS[divergence]
        benchmark = classified_map.benchmark
        habits = classified_map.get_habits()
        physics = classified_map.get_physics()
        base_steps = [
            {
                "number": i + 1,
                "action": "execute",
                "tool": (
                    benchmark.standard_tools[0]
                    if benchmark.standard_tools
                    else "ai"
                ),
                "params": {"instruction": desc},
                "description": desc,
                "checkpoint": i == 0,
                "idempotent": True,
                "timeout_ms": 30000,
            }
            for i, desc in enumerate(benchmark.standard_sequence)
        ]

        return [
            Path(
                id="A",
                label="Maximum Divergence",
                description=f"Breaking {len(habits)} habits",
                divergence_level=multipliers["A"],
                habits_broken=[h.element_name for h in habits],
                physics_respected=[p.element_name for p in physics],
                cross_domain_imports=benchmark.cross_domain_components[:3],
                steps=base_steps,
                tools_required=benchmark.standard_tools,
                risk_level="high",
                confidence=0.4,
            ),
            Path(
                id="B",
                label="Informed Hybrid",
                description=f"Breaking {len(habits) // 2} habits selectively",
                divergence_level=multipliers["B"],
                habits_broken=[
                    h.element_name for h in habits[: len(habits) // 2]
                ],
                physics_respected=[p.element_name for p in physics],
                cross_domain_imports=benchmark.cross_domain_components[:1],
                steps=base_steps,
                tools_required=benchmark.standard_tools,
                risk_level="medium",
                confidence=0.6,
            ),
            Path(
                id="C",
                label="Optimized Benchmark",
                description="Enhanced conventional approach",
                divergence_level=multipliers["C"],
                habits_broken=[],
                physics_respected=[p.element_name for p in physics],
                cross_domain_imports=[],
                steps=base_steps,
                tools_required=benchmark.standard_tools,
                risk_level="low",
                confidence=0.8,
            ),
        ]
