"""The Scout — maps the benchmark for any given goal.
PCT Components 01-04: Benchmark, Bandwidth, Average, Feedback Loop."""

import json
from typing import Any

from xyglue.thinking.models import BenchmarkMap, BenchmarkElement
from xyglue.goal.models import Goal


class Scout:
    """Maps how a task is TYPICALLY done. Not how to do it — how everyone else does it."""

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

    async def analyze(
        self,
        goal: Goal,
        available_tools: list[str],
        prior_templates: list[dict] | None = None,
    ) -> BenchmarkMap:
        if self.ai_client is None:
            return self._rule_based_analysis(goal, available_tools)

        template_str = ""
        if prior_templates:
            template_str = (
                f"\n\nPRIOR TEMPLATES:\n{json.dumps(prior_templates[:3], indent=2)}"
            )

        prompt = f"""You are {self.name}, a benchmark analysis agent.

Your job: Map how this task is TYPICALLY done. Not how YOU would do it — how does the average developer/team approach this?

GOAL: {goal.normalized}
AVAILABLE TOOLS: {', '.join(available_tools)}
CONTEXT: {json.dumps(goal.context, indent=2)}{template_str}

Respond with JSON:
{{
    "domain": "domain_name",
    "elements": [
        {{"name": "element", "description": "what it does", "tool": "which tool",
          "category": "approach|tool|pattern|assumption|sequence", "is_standard": true,
          "rationale": "why standard"}}
    ],
    "standard_tools": ["list"],
    "standard_sequence": ["Step 1", "Step 2"],
    "assumptions": ["assumption 1"],
    "cross_domain_components": ["components from OTHER domains that COULD apply but typically don't"]
}}

The cross_domain_components field is critical — identify available but typically unused components.
Respond ONLY with JSON."""

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

    def _parse_response(self, response: str, goal: Goal) -> BenchmarkMap:
        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())
            elements = [
                BenchmarkElement(
                    name=e.get("name", ""),
                    description=e.get("description", ""),
                    tool=e.get("tool", ""),
                    category=e.get("category", "approach"),
                    is_standard=e.get("is_standard", True),
                    rationale=e.get("rationale", ""),
                )
                for e in data.get("elements", [])
            ]
            return BenchmarkMap(
                goal_text=goal.normalized,
                domain=data.get("domain", ""),
                elements=elements,
                standard_tools=data.get("standard_tools", []),
                standard_sequence=data.get("standard_sequence", []),
                assumptions=data.get("assumptions", []),
                cross_domain_components=data.get("cross_domain_components", []),
            )
        except (json.JSONDecodeError, KeyError):
            return self._rule_based_analysis(goal, [])

    def _rule_based_analysis(
        self, goal: Goal, available_tools: list[str]
    ) -> BenchmarkMap:
        goal_lower = goal.normalized.lower()
        elements: list[BenchmarkElement] = []
        tools: list[str] = []
        sequence: list[str] = []

        if any(w in goal_lower for w in ["api", "rest", "endpoint", "server"]):
            elements.append(
                BenchmarkElement(
                    name="Web Framework",
                    tool="code",
                    category="tool",
                    rationale="Standard for API dev",
                )
            )
            elements.append(
                BenchmarkElement(
                    name="Database ORM",
                    tool="database",
                    category="tool",
                    rationale="Standard for persistence",
                )
            )
            tools = ["code", "database"]
            sequence = [
                "Setup project",
                "Define models",
                "Create routes",
                "Add middleware",
                "Test",
            ]
        elif any(w in goal_lower for w in ["scrape", "crawl", "extract", "download"]):
            elements.append(
                BenchmarkElement(
                    name="Browser Automation",
                    tool="browser",
                    category="tool",
                    rationale="Standard for scraping",
                )
            )
            tools = ["browser", "files"]
            sequence = ["Navigate", "Extract data", "Save results"]
        elif any(w in goal_lower for w in ["email", "send", "notify"]):
            elements.append(
                BenchmarkElement(
                    name="Email Service",
                    tool="email",
                    category="tool",
                    rationale="Standard for notifications",
                )
            )
            tools = ["email"]
            sequence = ["Compose", "Send"]
        else:
            elements.append(
                BenchmarkElement(
                    name="AI Reasoning",
                    tool="ai",
                    category="approach",
                    rationale="Default for unclassified",
                )
            )
            tools = ["ai"]
            sequence = ["Analyze goal", "Execute"]

        return BenchmarkMap(
            goal_text=goal.normalized,
            domain="general",
            elements=elements,
            standard_tools=tools,
            standard_sequence=sequence,
            assumptions=["Standard libraries available"],
            cross_domain_components=[],
        )
