"""Phase 3: simple multi-agent orchestrator (scaffold)."""
from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, List

from .ingestion import KBIngestionPipeline
from .retrieval import HybridRetriever
from .types import AgentResultEnvelope


@dataclass
class OrchestratorRoute:
    steps: List[str]
    mode: str


class OrchestratorRouter:
    """Lightweight router for vector/graph/synthesis agents."""

    def classify(self, query: str) -> OrchestratorRoute:
        q = query.lower()
        wants_graph = any(k in q for k in ["lineage", "impact", "downstream", "upstream", "graph"])
        wants_vector = any(k in q for k in ["similar", "semantic", "match", "search", "find"])

        if wants_graph and wants_vector:
            return OrchestratorRoute(steps=["vector_search", "graph_query", "synthesis"], mode="hybrid")
        if wants_graph:
            return OrchestratorRoute(steps=["graph_query", "synthesis"], mode="graph")
        if wants_vector:
            return OrchestratorRoute(steps=["vector_search", "synthesis"], mode="vector")
        return OrchestratorRoute(steps=["synthesis"], mode="fallback")


class OrchestratorExecutor:
    """Executes a minimal multi-agent flow using Phase 1/2 components."""

    def __init__(self, pipeline: KBIngestionPipeline):
        self.pipeline = pipeline
        self.router = OrchestratorRouter()
        self.retriever = HybridRetriever(pipeline.vector_store, pipeline.graph_store)

    def run_query(self, query: str, top_k: int = 5) -> Dict[str, AgentResultEnvelope]:
        route = self.router.classify(query)
        envelopes: Dict[str, AgentResultEnvelope] = {}

        if "vector_search" in route.steps or "graph_query" in route.steps:
            results = self.retriever.retrieve(query, top_k=top_k)
            items = [r.content for r in results]
            scores = [r.score for r in results]
            envelopes["retrieval"] = AgentResultEnvelope(
                items=items,
                scores=scores,
                citations=[],
                trace={"route": route.steps, "mode": route.mode},
                confidence=min(1.0, 0.5 + (len(items) * 0.05)),
            )

        # Simple synthesis: echo top item
        if envelopes.get("retrieval"):
            top = envelopes["retrieval"].items[0] if envelopes["retrieval"].items else ""
            envelopes["synthesis"] = AgentResultEnvelope(
                items=[top],
                scores=[1.0] if top else [],
                citations=envelopes["retrieval"].citations,
                trace={"source": "retrieval"},
                confidence=0.8 if top else 0.3,
            )
        else:
            envelopes["synthesis"] = AgentResultEnvelope(
                items=[],
                scores=[],
                citations=[],
                trace={"source": "none"},
                confidence=0.1,
            )

        return {"route": route, "envelopes": envelopes}
