from __future__ import annotations

import copy
import json
from pathlib import Path

import pytest

from src.services.ai_agent_action_owner_acceptance_event_bus import (
    load_latest_ai_agent_action_owner_acceptance_event_bus,
)

_REPO_ROOT = Path(__file__).resolve().parents[3]
_COMMITTED_SNAPSHOT = (
    _REPO_ROOT
    / "docs"
    / "evaluations"
    / "ai_agent_action_owner_acceptance_event_bus_2026-06-19.json"
)


def test_load_latest_ai_agent_action_owner_acceptance_event_bus_reads_newest_file(tmp_path):
    older = _snapshot(generated_at="2026-06-19T02:00:00+08:00")
    newer = _snapshot(generated_at="2026-06-19T02:10:00+08:00")
    (tmp_path / "ai_agent_action_owner_acceptance_event_bus_2026-06-18.json").write_text(
        json.dumps(older),
        encoding="utf-8",
    )
    (tmp_path / "ai_agent_action_owner_acceptance_event_bus_2026-06-19.json").write_text(
        json.dumps(newer),
        encoding="utf-8",
    )

    loaded = load_latest_ai_agent_action_owner_acceptance_event_bus(tmp_path)

    assert loaded["generated_at"] == "2026-06-19T02:10:00+08:00"
    assert loaded["program_status"]["current_task_id"] == "P2-411"
    assert loaded["program_status"]["next_task_id"] == "P2-412"
    assert loaded["rollups"]["owner_acceptance_lane_count"] == 6
    assert loaded["rollups"]["handoff_event_template_count"] == 6
    assert loaded["rollups"]["rag_memory_proposal_count"] == 4
    assert loaded["rollups"]["event_bus_publish_count"] == 0


def test_ai_agent_action_owner_acceptance_event_bus_requires_read_only_mode(tmp_path):
    snapshot = _snapshot()
    snapshot["program_status"]["read_only_mode"] = False
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="program_status"):
        load_latest_ai_agent_action_owner_acceptance_event_bus(tmp_path)


def test_ai_agent_action_owner_acceptance_event_bus_blocks_owner_acceptance_drift(tmp_path):
    snapshot = _snapshot()
    snapshot["event_bus_truth"]["owner_response_accepted"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="owner_response_accepted"):
        load_latest_ai_agent_action_owner_acceptance_event_bus(tmp_path)


def test_ai_agent_action_owner_acceptance_event_bus_blocks_event_publish(tmp_path):
    snapshot = _snapshot()
    snapshot["handoff_event_templates"][0]["event_bus_write_allowed"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="event_bus_write_allowed"):
        load_latest_ai_agent_action_owner_acceptance_event_bus(tmp_path)


def test_ai_agent_action_owner_acceptance_event_bus_blocks_rag_write(tmp_path):
    snapshot = _snapshot()
    snapshot["rag_memory_proposals"][0]["km_write_allowed"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="km_write_allowed"):
        load_latest_ai_agent_action_owner_acceptance_event_bus(tmp_path)


def test_ai_agent_action_owner_acceptance_event_bus_rejects_missing_lane_ref(tmp_path):
    snapshot = _snapshot()
    snapshot["handoff_event_templates"][0]["source_lane_ids"] = ["missing_lane"]
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="missing lanes"):
        load_latest_ai_agent_action_owner_acceptance_event_bus(tmp_path)


def test_ai_agent_action_owner_acceptance_event_bus_rejects_missing_source_ref(tmp_path):
    snapshot = _snapshot()
    snapshot["owner_acceptance_lanes"][0]["source_readback_ids"] = ["missing_source"]
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="missing source readbacks"):
        load_latest_ai_agent_action_owner_acceptance_event_bus(tmp_path)


def test_ai_agent_action_owner_acceptance_event_bus_requires_rollup_consistency(tmp_path):
    snapshot = _snapshot()
    snapshot["rollups"]["owner_acceptance_lane_count"] = 99
    _write_snapshot(tmp_path, snapshot)

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


def test_ai_agent_action_owner_acceptance_event_bus_rejects_private_terms(tmp_path):
    snapshot = _snapshot()
    snapshot["handoff_event_templates"][0]["display_name"] = "請顯示 " + "My request for " + "Codex"
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="forbidden public terms"):
        load_latest_ai_agent_action_owner_acceptance_event_bus(tmp_path)


def test_ai_agent_action_owner_acceptance_event_bus_fails_when_missing(tmp_path):
    with pytest.raises(FileNotFoundError):
        load_latest_ai_agent_action_owner_acceptance_event_bus(tmp_path)


def _snapshot(*, generated_at: str = "2026-06-19T02:10:00+08:00") -> dict:
    payload = json.loads(_COMMITTED_SNAPSHOT.read_text(encoding="utf-8"))
    cloned = copy.deepcopy(payload)
    cloned["generated_at"] = generated_at
    return cloned


def _write_snapshot(tmp_path, payload: dict) -> None:
    (tmp_path / "ai_agent_action_owner_acceptance_event_bus_2026-06-19.json").write_text(
        json.dumps(payload),
        encoding="utf-8",
    )
