import copy
import json

import pytest

from src.services.ai_agent_owner_approved_result_capture_dry_run import (
    load_latest_ai_agent_owner_approved_result_capture_dry_run,
)


def _write_snapshot(tmp_path, payload):
    path = tmp_path / "ai_agent_owner_approved_result_capture_dry_run_2026-06-13.json"
    path.write_text(json.dumps(payload), encoding="utf-8")
    return path


def test_load_latest_ai_agent_owner_approved_result_capture_dry_run():
    data = load_latest_ai_agent_owner_approved_result_capture_dry_run()

    assert data["schema_version"] == "ai_agent_owner_approved_result_capture_dry_run_v1"
    assert data["program_status"]["current_task_id"] == "P2-106"
    assert data["program_status"]["next_task_id"] == "P2-107"
    assert data["program_status"]["overall_completion_percent"] == 100
    assert data["prior_contract_readback"]["source_schema_version"] == "ai_agent_critic_reviewer_result_capture_v1"
    assert data["prior_contract_readback"]["approved_without_execution_meta_24h"] == 63
    assert data["dry_run_truth"]["owner_approval_required"] is True
    assert data["dry_run_truth"]["dry_run_preview_allowed"] is True
    assert data["dry_run_truth"]["owner_approval_received_count"] == 0
    assert data["dry_run_truth"]["dry_run_preview_generated_count"] == 0
    assert data["dry_run_truth"]["runtime_result_capture_write_enabled"] is False
    assert data["dry_run_truth"]["telegram_send_enabled"] is False
    assert data["rollups"]["result_capture_template_count"] == 5
    assert data["rollups"]["score_fixture_count"] == 5
    assert data["rollups"]["dry_run_gate_count"] == 7
    assert data["rollups"]["operator_action_count"] == 5
    assert data["rollups"]["result_capture_write_count"] == 0
    assert data["rollups"]["score_write_count"] == 0
    assert data["rollups"]["learning_write_count"] == 0
    assert data["rollups"]["playbook_trust_write_count"] == 0
    assert data["rollups"]["telegram_send_count"] == 0


def test_rejects_owner_approval_received_count(tmp_path):
    data = load_latest_ai_agent_owner_approved_result_capture_dry_run()
    bad = copy.deepcopy(data)
    bad["dry_run_truth"]["owner_approval_received_count"] = 1
    bad["rollups"]["owner_approval_received_count"] = 1
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="live counters"):
        load_latest_ai_agent_owner_approved_result_capture_dry_run(tmp_path)


def test_rejects_runtime_result_capture_write_enabled(tmp_path):
    data = load_latest_ai_agent_owner_approved_result_capture_dry_run()
    bad = copy.deepcopy(data)
    bad["dry_run_truth"]["runtime_result_capture_write_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="runtime write/send flags"):
        load_latest_ai_agent_owner_approved_result_capture_dry_run(tmp_path)


def test_rejects_template_write_enabled(tmp_path):
    data = load_latest_ai_agent_owner_approved_result_capture_dry_run()
    bad = copy.deepcopy(data)
    bad["result_capture_dry_run_templates"][0]["write_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="write_enabled"):
        load_latest_ai_agent_owner_approved_result_capture_dry_run(tmp_path)


def test_rejects_score_fixture_runtime_write(tmp_path):
    data = load_latest_ai_agent_owner_approved_result_capture_dry_run()
    bad = copy.deepcopy(data)
    bad["critic_reviewer_score_fixtures"][0]["runtime_score_write_enabled"] = True
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="runtime_score_write_enabled"):
        load_latest_ai_agent_owner_approved_result_capture_dry_run(tmp_path)


def test_rejects_missing_dry_run_gate(tmp_path):
    data = load_latest_ai_agent_owner_approved_result_capture_dry_run()
    bad = copy.deepcopy(data)
    bad["dry_run_gates"] = [
        gate for gate in bad["dry_run_gates"] if gate["gate_id"] != "gate_no_live_write_enforced"
    ]
    bad["rollups"]["dry_run_gate_count"] = len(bad["dry_run_gates"])
    bad["rollups"]["blocked_gate_count"] = sum(
        1 for gate in bad["dry_run_gates"] if gate["status"] == "blocked_by_policy"
    )
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="dry-run gates"):
        load_latest_ai_agent_owner_approved_result_capture_dry_run(tmp_path)


def test_rejects_forbidden_display_terms(tmp_path):
    data = load_latest_ai_agent_owner_approved_result_capture_dry_run()
    bad = copy.deepcopy(data)
    bad["operator_actions"][0]["operator_instruction"] = "不得顯示工作視窗內容"
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="forbidden display terms"):
        load_latest_ai_agent_owner_approved_result_capture_dry_run(tmp_path)


def test_rejects_rollup_mismatch(tmp_path):
    data = load_latest_ai_agent_owner_approved_result_capture_dry_run()
    bad = copy.deepcopy(data)
    bad["rollups"]["result_capture_template_count"] = 999
    _write_snapshot(tmp_path, bad)

    with pytest.raises(ValueError, match="rollup counts"):
        load_latest_ai_agent_owner_approved_result_capture_dry_run(tmp_path)
