from __future__ import annotations

from src.services.agent_market_integration_review import (
    run_agent_market_integration_review,
)


def test_integration_review_blocks_changed_nemotron_from_integration():
    report = run_agent_market_integration_review(
        watch_report=_watch_report("nemo_nemotron_fabric"),
        candidate_registry={
            "schema_version": "agent_replacement_candidates_v1",
            "candidates": [
                {
                    "candidate_id": "nemo_nemotron_fabric",
                    "display_name": "Nemotron",
                    "role": "agent_fabric_tool_model_evaluator",
                    "required_stage": "offline_replay",
                    "current_decision": "all_contract_tuned_nemotron_smokes_blocked_before_full_replay",
                    "latest_smoke_matrix": "docs/evaluations/agent_nemotron_contract_tuned_smoke_matrix_2026-06-02.json",
                }
            ],
        },
        scorecard=_scorecard("nemo_nemotron_fabric"),
        generated_at="2026-06-02T00:00:00+00:00",
    )

    assert report["policy"]["production_changes_approved"] is False
    assert report["summary"]["reviewed_candidates"] == 1
    assert report["summary"]["blocked_from_integration"] == 1
    review = report["reviews"][0]
    assert review["candidate_id"] == "nemo_nemotron_fabric"
    assert review["decision"] == "do_not_integrate_refresh_evidence_then_smoke_gate"
    assert review["readiness"]["stage"] == "blocked_existing_replay_evidence"
    assert "do_not_run_full_50_replay_until_smoke_gate_passes" in review["recommendations"]


def test_integration_review_requires_no_cost_adapter_for_unreplayed_candidate():
    report = run_agent_market_integration_review(
        watch_report=_watch_report("claude_agent_sdk_remediator"),
        candidate_registry={
            "schema_version": "agent_replacement_candidates_v1",
            "candidates": [
                {
                    "candidate_id": "claude_agent_sdk_remediator",
                    "display_name": "Claude Agent SDK Remediator",
                    "role": "devops_code_remediation_agent",
                    "required_stage": "offline_replay",
                }
            ],
        },
        scorecard=_scorecard("claude_agent_sdk_remediator"),
        generated_at="2026-06-02T00:00:00+00:00",
    )

    review = report["reviews"][0]
    assert review["decision"] == "do_not_integrate_prepare_no_cost_offline_adapter"
    assert review["readiness"]["stage"] == "not_yet_replayed"
    assert review["approval_boundary"]["approved_for_paid_api_calls"] is False
    assert "build_no_sdk_no_api_contract_adapter_first" in review["recommendations"]
    assert "50_record_hidden_label_replay_beats_openclaw_baseline" in review["unblock_conditions"]


def test_integration_review_actionable_scope_includes_source_failures():
    report = run_agent_market_integration_review(
        watch_report=_watch_report("google_adk_stack", changed=False, source_error="timeout"),
        candidate_registry={
            "schema_version": "agent_replacement_candidates_v1",
            "candidates": [
                {
                    "candidate_id": "google_adk_stack",
                    "display_name": "Google ADK Stack",
                    "role": "gemini_vertex_agent_stack",
                    "required_stage": "offline_replay",
                }
            ],
        },
        scorecard=_scorecard("google_adk_stack"),
        generated_at="2026-06-02T00:00:00+00:00",
    )

    assert report["inputs"]["review_scope"] == "actionable"
    assert report["summary"]["reviewed_candidates"] == 1
    assert report["reviews"][0]["market_watch"]["changed_sources"][0]["error"] == "timeout"


def test_integration_review_all_scope_reviews_unchanged_candidates():
    report = run_agent_market_integration_review(
        watch_report=_watch_report("microsoft_agent_framework", changed=False),
        candidate_registry={
            "schema_version": "agent_replacement_candidates_v1",
            "candidates": [
                {
                    "candidate_id": "microsoft_agent_framework",
                    "display_name": "Microsoft Agent Framework",
                    "role": "enterprise_workflow_agent_stack",
                    "required_stage": "offline_replay",
                }
            ],
        },
        scorecard=_scorecard("microsoft_agent_framework"),
        review_scope="all",
        generated_at="2026-06-02T00:00:00+00:00",
    )

    assert report["inputs"]["review_scope"] == "all"
    assert report["summary"]["reviewed_candidates"] == 1
    assert report["reviews"][0]["decision"] == "do_not_integrate_prepare_no_cost_offline_adapter"


def test_integration_review_keeps_watch_only_candidates_out_of_replay():
    report = run_agent_market_integration_review(
        watch_report=_watch_report("hermes_agent_personal_platform", changed=False),
        candidate_registry={
            "schema_version": "agent_replacement_candidates_v1",
            "candidates": [
                {
                    "candidate_id": "hermes_agent_personal_platform",
                    "display_name": "Hermes Agent",
                    "role": "personal_agent_platform_candidate",
                    "evaluation_priority": "watch_only",
                    "required_stage": "watch_only_primary_source_monitoring",
                }
            ],
        },
        scorecard={"schema_version": "agent_market_capability_scorecard_v1", "candidates": []},
        review_scope="all",
        generated_at="2026-06-04T00:00:00+00:00",
    )

    review = report["reviews"][0]
    assert review["decision"] == "do_not_integrate_watch_only_primary_source_monitoring"
    assert review["readiness"]["stage"] == "watch_only_primary_source_monitoring"
    assert "keep_candidate_in_watch_registry_only" in review["recommendations"]
    assert "explicit_priority_upgrade_before_replay" in review["unblock_conditions"]
    assert "50_record_hidden_label_replay_beats_openclaw_baseline" not in review["unblock_conditions"]


def _watch_report(candidate_id: str, *, changed: bool = True, source_error: str | None = None) -> dict:
    http_status = None if source_error else 200
    source_status = "error" if source_error else "ok"
    return {
        "schema_version": "agent_market_watch_report_v1",
        "generated_at": "2026-06-02T00:00:00+00:00",
        "mode": "live",
        "summary": {
            "candidate_count": 1,
            "source_count": 1,
            "changed_candidates": 1 if changed else 0,
            "watch_only_candidates": 0 if changed else 1,
            "integration_queue_count": 1 if changed else 0,
            "failure_count": 1 if source_error else 0,
        },
        "candidates": [
            {
                "candidate_id": candidate_id,
                "display_name": candidate_id,
                "recommended_role": "specialist",
                "requires_cost_approval": True,
                "requires_dependency_approval": True,
                "changed": changed,
                "decision": "changed_requires_replay_readiness_review",
                "recommended_actions": ["refresh_market_capability_evidence"],
                "sources": [
                    {
                        "source_id": "docs",
                        "type": "docs",
                        "url": "https://example.com",
                        "status": source_status,
                        "http_status": http_status,
                        "changed_since_reference": changed,
                        "content_hash": "abc123",
                        "error": source_error,
                    }
                ],
            }
        ],
    }


def _scorecard(candidate_id: str) -> dict:
    return {
        "schema_version": "agent_market_capability_scorecard_v1",
        "scoring_version": "market_capability_v1",
        "candidates": [
            {
                "candidate_id": candidate_id,
                "rank": 3,
                "total_score": 0.8,
                "replay_priority": "p0_replay",
                "beats_baseline_capability": True,
                "strengths": ["observability_tracing"],
                "gaps": ["local_private_deploy"],
                "risks": ["requires approval"],
            }
        ],
    }
