from __future__ import annotations

import copy
import json
from pathlib import Path

import pytest

from src.services.ai_agent_report_no_write_analysis_runtime import (
    load_latest_ai_agent_report_no_write_analysis_runtime,
)

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


def test_load_latest_ai_agent_report_no_write_analysis_runtime_reads_newest_file(tmp_path):
    older = _snapshot(generated_at="2026-06-17T00:00:00+08:00")
    newer = _snapshot(generated_at="2026-06-18T00:00:00+08:00")
    (tmp_path / "ai_agent_report_no_write_analysis_runtime_2026-06-17.json").write_text(
        json.dumps(older),
        encoding="utf-8",
    )
    (tmp_path / "ai_agent_report_no_write_analysis_runtime_2026-06-18.json").write_text(
        json.dumps(newer),
        encoding="utf-8",
    )

    loaded = load_latest_ai_agent_report_no_write_analysis_runtime(tmp_path)

    assert loaded["generated_at"] == "2026-06-18T00:00:00+08:00"
    assert loaded["program_status"]["current_task_id"] == "P2-407"
    assert loaded["program_status"]["next_task_id"] == "P2-408"
    assert loaded["program_status"]["read_only_mode"] is True
    assert loaded["rollups"]["live_ai_analysis_count"] == 0
    assert loaded["rollups"]["telegram_send_count"] == 0


def test_ai_agent_report_no_write_analysis_runtime_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_report_no_write_analysis_runtime(tmp_path)


def test_ai_agent_report_no_write_analysis_runtime_blocks_live_ai_runtime(tmp_path):
    snapshot = _snapshot()
    snapshot["analysis_truth"]["ai_analysis_runtime_enabled"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="analysis truth flags"):
        load_latest_ai_agent_report_no_write_analysis_runtime(tmp_path)


def test_ai_agent_report_no_write_analysis_runtime_blocks_telegram_send(tmp_path):
    snapshot = _snapshot()
    snapshot["telegram_policy"]["telegram_send_allowed"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="telegram_policy"):
        load_latest_ai_agent_report_no_write_analysis_runtime(tmp_path)


def test_ai_agent_report_no_write_analysis_runtime_requires_source_schemas(tmp_path):
    snapshot = _snapshot()
    snapshot["source_readbacks"] = snapshot["source_readbacks"][:-1]
    snapshot["rollups"]["source_readback_count"] = len(snapshot["source_readbacks"])
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="missing source schemas"):
        load_latest_ai_agent_report_no_write_analysis_runtime(tmp_path)


def test_ai_agent_report_no_write_analysis_runtime_requires_rollup_consistency(tmp_path):
    snapshot = _snapshot()
    snapshot["rollups"]["draft_recommendation_count"] = 99
    _write_snapshot(tmp_path, snapshot)

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


def test_ai_agent_report_no_write_analysis_runtime_rejects_private_terms(tmp_path):
    snapshot = _snapshot()
    snapshot["draft_recommendations"][0]["draft_solution"] = "請把 In app browser 內容放進前端"
    _write_snapshot(tmp_path, snapshot)

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


def test_ai_agent_report_no_write_analysis_runtime_fails_when_missing(tmp_path):
    with pytest.raises(FileNotFoundError):
        load_latest_ai_agent_report_no_write_analysis_runtime(tmp_path)


def _snapshot(*, generated_at: str = "2026-06-18T15:20: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_report_no_write_analysis_runtime_2026-06-18.json").write_text(
        json.dumps(payload),
        encoding="utf-8",
    )
