"""
Market Candidate Replay Adapter Harness
=======================================

Builds fail-closed replay outputs for real market candidate adapters.

This module does not call external SDKs or production systems. It gives each
market candidate an executable contract probe so adapter authors can verify the
AWOOOI replay input/output boundary before wiring paid or stateful services.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from src.services.agent_replay_input import assert_no_evaluation_label_leak


@dataclass(frozen=True)
class MarketCandidateSpec:
    """Static metadata for one market replacement candidate."""

    candidate_id: str
    candidate_role: str
    display_name: str
    connector_hint: str
    replay_priority: str
    env_hints: tuple[str, ...] = ()

    def to_dict(self) -> dict[str, Any]:
        return {
            "candidate_id": self.candidate_id,
            "candidate_role": self.candidate_role,
            "display_name": self.display_name,
            "connector_hint": self.connector_hint,
            "replay_priority": self.replay_priority,
            "env_hints": list(self.env_hints),
        }


MARKET_CANDIDATE_SPECS: dict[str, MarketCandidateSpec] = {
    "openai_agents_sdk_coordinator": MarketCandidateSpec(
        candidate_id="openai_agents_sdk_coordinator",
        candidate_role="coordinator_orchestrator",
        display_name="OpenAI Agents SDK Coordinator",
        connector_hint="OpenAI Agents SDK adapter with tracing and guardrails",
        replay_priority="p0_replay",
        env_hints=("OPENAI_API_KEY",),
    ),
    "nemo_nemotron_fabric": MarketCandidateSpec(
        candidate_id="nemo_nemotron_fabric",
        candidate_role="agent_fabric_tool_model_evaluator",
        display_name="NVIDIA NeMo Agent Toolkit + Nemotron Fabric",
        connector_hint="NeMo Agent Toolkit / NIM / Nemotron local or private adapter",
        replay_priority="p0_replay",
        env_hints=("NVIDIA_API_KEY", "NIM_BASE_URL"),
    ),
    "langgraph_incident_kernel": MarketCandidateSpec(
        candidate_id="langgraph_incident_kernel",
        candidate_role="durable_incident_workflow_kernel",
        display_name="LangGraph Incident Kernel",
        connector_hint="LangGraph stateful workflow adapter",
        replay_priority="p0_replay",
        env_hints=("LANGSMITH_API_KEY",),
    ),
    "claude_agent_sdk_remediator": MarketCandidateSpec(
        candidate_id="claude_agent_sdk_remediator",
        candidate_role="devops_code_remediation_agent",
        display_name="Claude Agent SDK Remediator",
        connector_hint="Claude Agent SDK adapter for DevOps remediation",
        replay_priority="p0_replay",
        env_hints=("ANTHROPIC_API_KEY",),
    ),
    "claude_managed_agents_sandbox": MarketCandidateSpec(
        candidate_id="claude_managed_agents_sandbox",
        candidate_role="managed_agent_sandbox",
        display_name="Claude Managed Agents Sandbox",
        connector_hint="Claude Managed Agents sandbox adapter",
        replay_priority="p1_replay",
        env_hints=("ANTHROPIC_API_KEY",),
    ),
    "google_adk_stack": MarketCandidateSpec(
        candidate_id="google_adk_stack",
        candidate_role="gemini_vertex_agent_stack",
        display_name="Google Agent Development Kit Stack",
        connector_hint="Google ADK / Vertex AI Agent Engine adapter",
        replay_priority="p1_replay",
        env_hints=("GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_API_KEY"),
    ),
    "microsoft_agent_framework": MarketCandidateSpec(
        candidate_id="microsoft_agent_framework",
        candidate_role="enterprise_workflow_agent_stack",
        display_name="Microsoft Agent Framework",
        connector_hint="Microsoft Agent Framework workflow adapter",
        replay_priority="p1_replay",
        env_hints=("AZURE_OPENAI_API_KEY",),
    ),
    "crewai_flows_crews": MarketCandidateSpec(
        candidate_id="crewai_flows_crews",
        candidate_role="rapid_agent_team_prototype",
        display_name="CrewAI Flows + Crews",
        connector_hint="CrewAI flow adapter",
        replay_priority="watch",
        env_hints=(),
    ),
}


def get_market_candidate_spec(candidate_id: str) -> MarketCandidateSpec:
    """Return static metadata for a registered market candidate."""
    try:
        return MARKET_CANDIDATE_SPECS[candidate_id]
    except KeyError as exc:
        known = ", ".join(sorted(MARKET_CANDIDATE_SPECS))
        raise ValueError(f"unknown market candidate_id {candidate_id!r}; known: {known}") from exc


def build_contract_probe_result(
    candidate_input: dict[str, Any],
    *,
    candidate_id: str,
    reason: str = "external_candidate_adapter_not_configured",
) -> dict[str, Any]:
    """Build a safe result proving the adapter contract, not candidate quality."""
    assert_no_evaluation_label_leak(candidate_input)
    spec = get_market_candidate_spec(candidate_id)
    incident_id = str(candidate_input.get("incident_id", "")).strip()
    run_id = str(candidate_input.get("run_id", "")).strip()
    if not incident_id or not run_id:
        raise ValueError("candidate input must include incident_id and run_id")

    return {
        "schema_version": "agent_candidate_replay_result_v1",
        "run_id": run_id,
        "incident_id": incident_id,
        "candidate_id": spec.candidate_id,
        "candidate_role": spec.candidate_role,
        "proposed_action": "",
        "action_plan": [],
        "risk_level": "low",
        "requires_human_approval": True,
        "blocked_by_policy": True,
        "fallback_used": True,
        "trace_complete": True,
        "trace_events": [
            {"type": "input_loaded"},
            {"type": "answer_key_leak_check_passed"},
            {"type": "external_execution_blocked", "reason": reason},
        ],
        "rca_correct": None,
        "tool_dry_run_pass": None,
        "repair_success": None,
        "false_repair": False,
        "latency_ms": 0,
        "cost_usd": 0,
        "error": reason,
        "metadata": {
            "adapter_mode": "contract_probe",
            "connector_hint": spec.connector_hint,
            "env_hints": list(spec.env_hints),
            "not_replacement_evidence": True,
            "replay_priority": spec.replay_priority,
        },
    }


def build_contract_probe_results(
    candidate_inputs: list[dict[str, Any]],
    *,
    candidate_id: str,
    reason: str = "external_candidate_adapter_not_configured",
) -> list[dict[str, Any]]:
    """Build safe contract-probe results for many candidate inputs."""
    return [
        build_contract_probe_result(
            candidate_input,
            candidate_id=candidate_id,
            reason=reason,
        )
        for candidate_input in candidate_inputs
    ]
