from __future__ import annotations

import json

import pytest

from src.services.agent_market_governance_snapshot import (
    build_agent_market_governance_snapshot,
    load_latest_agent_market_governance_snapshot,
)


def test_governance_snapshot_keeps_openclaw_as_production_core_without_approvals():
    snapshot = build_agent_market_governance_snapshot(
        watch_report=_watch_report(),
        integration_review=_integration_review(),
        discovery_classification=_classification(),
        promotion_review=_promotion_review(),
        candidate_registry=_registry(),
        generated_at="2026-06-04T00:00:00+00:00",
    )

    assert snapshot["current_decision"] == "openclaw_remains_production_decision_core"
    assert snapshot["summary"]["candidate_count"] == 2
    assert snapshot["summary"]["blocked_from_integration"] == 1
    assert snapshot["summary"]["eligible_for_market_scorecard_prescreen"] == 1
    assert snapshot["summary"]["replay_candidates_approved"] == 0
    assert snapshot["summary"]["replacement_decisions_approved"] == 0
    assert snapshot["policy"]["replacement_decision_allowed"] is False
    assert snapshot["evaluation_cadence"] == {
        "workflow": ".gitea/workflows/agent-market-watch.yaml",
        "schedule": "weekly_monday_0900_asia_taipei",
        "timezone": "Asia/Taipei",
        "next_scheduled_run_at": "2026-06-08T09:00:00+08:00",
        "trigger_modes": [
            "scheduled_weekly",
            "manual_dispatch",
            "operator_triggered_after_primary_source_signal",
        ],
        "primary_source_policy": "primary_sources_only_no_llm_no_sdk_no_paid_api",
        "operator_review_gate": (
            "priority_upgrade_required_before_scorecard_replay_sdk_api_shadow_canary_or_production"
        ),
    }
    assert snapshot["market_watch_health"] == {
        "status": "healthy",
        "freshness_sla_hours": 168,
        "stale_grace_hours": 6,
        "stale_after": "2026-06-08T15:00:00+08:00",
        "source_failures_block_priority_upgrade": False,
        "blocked_from_integration": 1,
        "operator_blockers": [],
    }
    assert snapshot["candidate_groups"]["production_baseline"] == ["openclaw_incumbent"]
    assert snapshot["candidate_groups"]["watch_only_scorecard_prescreen_ready"] == [
        "hermes_agent_personal_platform"
    ]
    assert snapshot["candidate_statuses"] == [
        {
            "candidate_id": "openclaw_incumbent",
            "display_name": "openclaw_incumbent",
            "role": "",
            "evaluation_priority": "baseline",
            "gate_status": "production_baseline",
            "current_gate": "production_decision_core",
            "required_next_gate": "formal_replacement_adr_and_promotion_gate_required",
            "integration_decision": "",
            "score": None,
            "evidence": {
                "latest_replay_summary": None,
                "latest_smoke_gate": None,
                "latest_smoke_matrix": None,
                "latest_smoke_model": None,
            },
            "approvals": {
                "replay": False,
                "sdk_install": False,
                "paid_api": False,
                "shadow_or_canary": False,
                "production_routing": False,
            },
            "operator_blockers": [],
        },
        {
            "candidate_id": "hermes_agent_personal_platform",
            "display_name": "Hermes Agent",
            "role": "personal_agent_platform_candidate",
            "evaluation_priority": "watch_only",
            "gate_status": "watch_only_prescreen_ready",
            "current_gate": "watch_only_primary_source_monitoring",
            "required_next_gate": "operator_priority_upgrade_then_market_scorecard_prescreen",
            "integration_decision": "do_not_integrate_watch_only_primary_source_monitoring",
            "score": None,
            "evidence": {
                "latest_replay_summary": None,
                "latest_smoke_gate": None,
                "latest_smoke_matrix": None,
                "latest_smoke_model": None,
            },
            "approvals": {
                "replay": False,
                "sdk_install": False,
                "paid_api": False,
                "shadow_or_canary": False,
                "production_routing": False,
            },
            "operator_blockers": [],
        },
    ]
    assert snapshot["operator_decision_queue"] == [
        {
            "candidate_id": "hermes_agent_personal_platform",
            "display_name": "Hermes Agent",
            "priority": 30,
            "queue_status": "operator_priority_review",
            "recommended_action": "operator_priority_upgrade_then_market_scorecard_prescreen",
            "approval_boundary": {
                "replacement_adr_required": True,
                "priority_upgrade_required": True,
                "market_scorecard_update_required": True,
                "replay_approval_required": True,
                "sdk_install_approval_required": True,
                "paid_api_approval_required": False,
                "shadow_or_canary_approval_required": True,
                "production_routing_approval_required": True,
            },
            "risk_notes": [],
            "evidence_refs": [],
        },
        {
            "candidate_id": "openclaw_incumbent",
            "display_name": "openclaw_incumbent",
            "priority": 90,
            "queue_status": "baseline_protected",
            "recommended_action": (
                "keep_openclaw_as_production_decision_core_until_formal_replacement_adr"
            ),
            "approval_boundary": {
                "replacement_adr_required": True,
                "priority_upgrade_required": False,
                "market_scorecard_update_required": False,
                "replay_approval_required": False,
                "sdk_install_approval_required": False,
                "paid_api_approval_required": False,
                "shadow_or_canary_approval_required": False,
                "production_routing_approval_required": True,
            },
            "risk_notes": ["no_candidate_has_formal_replacement_approval"],
            "evidence_refs": [],
        },
    ]
    assert "replace_openclaw" in snapshot["forbidden_actions_without_new_approval"]


def test_governance_snapshot_blocks_market_health_when_sources_or_queue_are_not_clean():
    snapshot = build_agent_market_governance_snapshot(
        watch_report=_watch_report(failure_count=2, integration_queue_count=1),
        integration_review=_integration_review(),
        discovery_classification=_classification(recommended_watch_additions=1),
        promotion_review=_promotion_review(),
        candidate_registry=_registry(),
        generated_at="2026-06-04T00:00:00+00:00",
    )

    assert snapshot["market_watch_health"]["status"] == "blocked"
    assert snapshot["market_watch_health"]["source_failures_block_priority_upgrade"] is True
    assert snapshot["market_watch_health"]["operator_blockers"] == [
        "source_failures_present",
        "unclassified_discovery_watch_additions_remaining",
        "integration_queue_not_empty",
    ]


def test_load_latest_governance_snapshot_reads_newest_file(tmp_path):
    older = build_agent_market_governance_snapshot(
        watch_report=_watch_report(),
        integration_review=_integration_review(),
        discovery_classification=_classification(),
        promotion_review=_promotion_review(),
        candidate_registry=_registry(),
        generated_at="2026-06-03T00:00:00+00:00",
    )
    newer = build_agent_market_governance_snapshot(
        watch_report=_watch_report(candidate_count=3),
        integration_review=_integration_review(blocked_from_integration=2),
        discovery_classification=_classification(),
        promotion_review=_promotion_review(),
        candidate_registry=_registry(),
        generated_at="2026-06-04T00:00:00+00:00",
    )
    (tmp_path / "agent_market_governance_snapshot_2026-06-03.json").write_text(
        json.dumps(older),
        encoding="utf-8",
    )
    (tmp_path / "agent_market_governance_snapshot_2026-06-04.json").write_text(
        json.dumps(newer),
        encoding="utf-8",
    )

    loaded = load_latest_agent_market_governance_snapshot(tmp_path)

    assert loaded["generated_at"] == "2026-06-04T00:00:00+00:00"
    assert loaded["summary"]["candidate_count"] == 3
    assert loaded["summary"]["blocked_from_integration"] == 2


def test_load_latest_governance_snapshot_fails_when_missing(tmp_path):
    with pytest.raises(FileNotFoundError):
        load_latest_agent_market_governance_snapshot(tmp_path)


def _registry() -> dict:
    return {
        "schema_version": "agent_replacement_candidates_v1",
        "candidates": [
            {
                "candidate_id": "openclaw_incumbent",
                "display_name": "openclaw_incumbent",
                "evaluation_priority": "baseline",
                "required_stage": "export_baseline",
            },
            {
                "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",
            },
        ],
    }


def _watch_report(
    candidate_count: int = 2,
    failure_count: int = 0,
    integration_queue_count: int = 0,
) -> dict:
    return {
        "schema_version": "agent_market_watch_report_v1",
        "generated_at": "2026-06-04T00:00:00+00:00",
        "summary": {
            "candidate_count": candidate_count,
            "source_count": 3,
            "failure_count": failure_count,
            "changed_candidates": 0,
            "integration_queue_count": integration_queue_count,
        },
    }


def _integration_review(blocked_from_integration: int = 1) -> dict:
    return {
        "schema_version": "agent_market_integration_review_v1",
        "generated_at": "2026-06-04T00:00:00+00:00",
        "policy": {"replacement_decision_allowed": False},
        "summary": {
            "blocked_from_integration": blocked_from_integration,
            "production_changes_approved": 0,
            "shadow_or_canary_approved": 0,
        },
        "reviews": [
            {
                "candidate_id": "hermes_agent_personal_platform",
                "decision": "do_not_integrate_watch_only_primary_source_monitoring",
            }
        ],
    }


def _classification(recommended_watch_additions: int = 0) -> dict:
    return {
        "schema_version": "agent_market_discovery_classification_v1",
        "generated_at": "2026-06-04T00:00:00+00:00",
        "summary": {
            "recommended_watch_additions": recommended_watch_additions,
            "production_changes_approved": 0,
            "shadow_or_canary_approved": 0,
        },
    }


def _promotion_review() -> dict:
    return {
        "schema_version": "agent_market_watch_promotion_review_v1",
        "generated_at": "2026-06-04T00:00:00+00:00",
        "policy": {"replacement_decision_allowed": False},
        "summary": {
            "watch_only_candidates_reviewed": 1,
            "eligible_for_market_scorecard_prescreen": 1,
            "priority_upgrades_approved": 0,
            "market_scorecard_updates_approved": 0,
            "replay_candidates_approved": 0,
            "sdk_installations_approved": 0,
            "paid_api_calls_approved": 0,
            "production_changes_approved": 0,
            "shadow_or_canary_approved": 0,
        },
        "reviews": [
            {
                "candidate_id": "hermes_agent_personal_platform",
                "eligible_for_market_scorecard_prescreen": True,
                "display_name": "Hermes Agent",
                "decision": "eligible_for_operator_priority_review_before_market_scorecard",
                "integration_stage": "watch_only_primary_source_monitoring",
                "required_next_gate": "operator_priority_upgrade_then_market_scorecard_prescreen",
                "role": "personal_agent_platform_candidate",
                "approved_for_replay": False,
                "approved_for_sdk_install": False,
                "approved_for_paid_api_calls": False,
                "approved_for_shadow_or_canary": False,
                "blockers": [],
            }
        ],
    }
