"""API routes wrapping OrxaqEngine for the dashboard.

Each route returns a JSON-serializable dict. The server module
maps HTTP paths to these routes. Stdlib-only (ADR-028).
"""

from __future__ import annotations

from orxaq.orchestration.integration import OrxaqEngine


class OrxaqAPI:
    """HTTP API wrapping OrxaqEngine for the dashboard."""

    def __init__(self) -> None:
        self.engine = OrxaqEngine()
        self.engine.load_credit_ontology()
        self._synthetic_data: list[dict] | None = None

    @property
    def data(self) -> list[dict]:
        """Lazy-load synthetic data."""
        if self._synthetic_data is None:
            self._synthetic_data = self.engine.generate_synthetic(n=500, seed=42)
        return self._synthetic_data

    def handle(self, path: str) -> tuple[dict, int]:
        """Route a request path to the appropriate handler.

        Returns (response_dict, status_code).
        """
        from collections.abc import Callable

        routes: dict[str, Callable[[], dict]] = {
            "/api/status": self._status,
            "/api/ontology": self._ontology,
            "/api/ecl": self._ecl,
            "/api/stress": self._stress,
            "/api/fairness": self._fairness,
            "/api/discover": self._discover,
            "/api/validate": self._validate,
            "/api/audit": self._audit,
        }

        handler = routes.get(path)
        if handler is None:
            return {"error": "not_found", "path": path}, 404

        return handler(), 200

    def _status(self) -> dict:
        return self.engine.status()

    def _ontology(self) -> dict:
        dag = self.engine.world_dag
        entities = []
        for eid, entity in sorted(dag._entities.items()):
            entities.append(
                {
                    "id": eid,
                    "name": entity.name,
                    "causal_role": entity.causal_role.value,
                    "variable_type": entity.variable_type.value,
                }
            )
        edges = []
        for edge in dag._edges.values():
            edges.append(
                {
                    "source": edge.source,
                    "target": edge.target,
                    "mechanism": edge.mechanism,
                    "confidence": edge.confidence,
                    "soliton_score": edge.soliton_score,
                }
            )
        return {"entities": entities, "edges": edges, "entity_count": len(entities)}

    def _ecl(self) -> dict:
        result = self.engine.compute_ecl(self.data)
        return {
            "total_ecl": result.total_ecl,
            "pd_mean": result.pd_mean,
            "lgd": result.lgd,
            "ead_total": result.ead_total,
            "horizon_quarters": result.horizon_quarters,
            "horizon_method": result.horizon_method,
            "confidence_band": list(result.confidence_band),
            "ecl_by_segment": result.ecl_by_segment,
        }

    def _stress(self) -> dict:
        return self.engine.stress_test(self.data, "severely_adverse")

    def _fairness(self) -> dict:
        decomp = self.engine.fairness_audit(protected="age")
        return {
            "protected_var": decomp.protected_var,
            "outcome_var": decomp.outcome_var,
            "total_effect": decomp.total_effect,
            "direct_effect": decomp.direct_effect,
            "indirect_effects": decomp.indirect_effects,
            "legitimate_paths": [list(p) for p in decomp.legitimate_paths],
            "concerning_paths": [list(p) for p in decomp.concerning_paths],
        }

    def _discover(self) -> dict:
        result = self.engine.discover_structure(
            self.data,
            variables=["unemployment_rate", "income", "credit_score", "dti", "default_flag"],
            use_consensus=True,
        )
        return {
            "edges": [
                {
                    "source": e.source,
                    "target": e.target,
                    "directed": e.directed,
                    "confidence": e.confidence,
                    "supporters": list(e.supporters),
                }
                for e in result.edges
            ],
            "algorithms_used": list(result.algorithms_used),
            "agreement_threshold": result.agreement_threshold,
        }

    def _validate(self) -> dict:
        report = self.engine.validate_dag(self.data)
        return {
            "total_implications": report.total_implications,
            "violations": report.violations,
            "violation_rate": report.violation_rate,
            "passed": report.passed,
        }

    def _audit(self) -> dict:
        entries = self.engine.audit_log.entries()
        return {
            "entries": [
                {
                    "timestamp": e.timestamp,
                    "action": e.action,
                    "actor": e.actor,
                    "details": e.details,
                }
                for e in entries[-50:]
            ]
        }
