from __future__ import annotations

import json

import pytest

from src.services.dependency_supply_chain_drift_monitor import (
    load_latest_dependency_supply_chain_drift_monitor,
)


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

    loaded = load_latest_dependency_supply_chain_drift_monitor(tmp_path)

    assert loaded["generated_at"] == "2026-06-18T00:00:00+08:00"
    assert loaded["program_status"]["overall_completion_percent"] == 100
    assert loaded["program_status"]["current_task_id"] == "P2-004"
    assert loaded["program_status"]["next_task_id"] == "P2-406B"
    assert loaded["monitor_boundaries"]["external_cve_lookup_allowed"] is False
    assert loaded["monitor_boundaries"]["telegram_send_allowed"] is False


def test_dependency_supply_chain_drift_monitor_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="read_only_mode"):
        load_latest_dependency_supply_chain_drift_monitor(tmp_path)


def test_dependency_supply_chain_drift_monitor_blocks_external_lookup(tmp_path):
    snapshot = _snapshot()
    snapshot["monitor_boundaries"]["external_cve_lookup_allowed"] = True
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="monitor boundaries"):
        load_latest_dependency_supply_chain_drift_monitor(tmp_path)


def test_dependency_supply_chain_drift_monitor_requires_rollup_consistency(tmp_path):
    snapshot = _snapshot()
    snapshot["rollups"]["drift_candidate_count"] = 99
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="drift_candidate_count"):
        load_latest_dependency_supply_chain_drift_monitor(tmp_path)


def test_dependency_supply_chain_drift_monitor_requires_candidate_evidence(tmp_path):
    snapshot = _snapshot()
    snapshot["drift_candidates"][0]["evidence_refs"] = []
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="evidence_refs"):
        load_latest_dependency_supply_chain_drift_monitor(tmp_path)


def test_dependency_supply_chain_drift_monitor_requires_owner_action_link(tmp_path):
    snapshot = _snapshot()
    snapshot["drift_candidates"][0]["next_owner_action"] = "missing_action"
    _write_snapshot(tmp_path, snapshot)

    with pytest.raises(ValueError, match="unknown owner action"):
        load_latest_dependency_supply_chain_drift_monitor(tmp_path)


def test_dependency_supply_chain_drift_monitor_fails_when_missing(tmp_path):
    with pytest.raises(FileNotFoundError):
        load_latest_dependency_supply_chain_drift_monitor(tmp_path)


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


def _snapshot(
    *,
    generated_at: str = "2026-06-18T00:00:00+08:00",
    completion: int = 100,
) -> dict:
    return {
        "schema_version": "dependency_supply_chain_drift_monitor_v1",
        "generated_at": generated_at,
        "program_status": {
            "overall_completion_percent": completion,
            "current_priority": "P2",
            "current_task_id": "P2-004",
            "next_task_id": "P2-406B",
            "read_only_mode": True,
            "runtime_authority": "repo_only",
            "status_note": "只讀監控。",
        },
        "source_refs": ["docs/evaluations/package_supply_chain_inventory_2026-06-04.json"],
        "rollups": {
            "source_snapshot_count": 2,
            "stale_source_snapshot_count": 1,
            "monitor_check_count": 1,
            "drift_candidate_count": 2,
            "action_required_candidate_count": 2,
            "owner_action_count": 2,
            "blocked_operation_count": 20,
            "by_domain": {"python": 1, "docker": 1},
            "action_required_drift_candidate_ids": [
                "python_manifest_drift",
                "docker_digest_gap",
            ],
        },
        "source_snapshot_readbacks": [
            _source_snapshot("package_supply_chain_inventory", "stale_action_required"),
            _source_snapshot("ai_agent_version_freshness_snapshot", "recent_action_required"),
        ],
        "monitor_checks": [
            {
                "check_id": "python_manifest_authority_drift_readback",
                "domain": "python",
                "owner_agent": "hermes",
                "status": "action_required",
                "current_signal": "manifest drift",
                "evidence_refs": ["apps/api/pyproject.toml"],
                "blocked_now": ["package upgrade"],
                "next_action": "prepare_python_manifest_authority_packet",
            }
        ],
        "drift_candidates": [
            _candidate(
                "python_manifest_drift",
                "python",
                "prepare_python_manifest_authority_packet",
            ),
            _candidate("docker_digest_gap", "docker", "prepare_docker_digest_pin_packet"),
        ],
        "owner_actions": [
            _owner_action("prepare_python_manifest_authority_packet", "openclaw"),
            _owner_action("prepare_docker_digest_pin_packet", "openclaw"),
        ],
        "telegram_policy": {
            "status": "draft_only_no_send",
            "direct_send_allowed": False,
            "gateway_queue_write_allowed": False,
            "success_quiet": True,
            "failure_digest_after_approval": True,
            "draft_only_outputs": ["digest draft"],
        },
        "agent_roles": [
            {
                "agent_id": "openclaw",
                "role": "仲裁",
                "autonomy_level": "L2",
                "approval_gate": "human_review_required",
                "outputs": ["risk packet"],
            }
        ],
        "next_actions": [
            {
                "task_id": "P2-406B",
                "priority": "P2",
                "summary": "下一步",
                "gate": "no send",
            }
        ],
        "monitor_boundaries": {
            "read_only_repo_monitor_allowed": True,
            "schedule_activation_allowed": False,
            "workflow_write_allowed": False,
            "external_cve_lookup_allowed": False,
            "external_license_lookup_allowed": False,
            "registry_lookup_allowed": False,
            "agent_market_external_lookup_allowed": False,
            "package_installation_allowed": False,
            "package_upgrade_allowed": False,
            "lockfile_write_allowed": False,
            "docker_build_allowed": False,
            "image_pull_allowed": False,
            "image_rebuild_allowed": False,
            "registry_push_allowed": False,
            "pr_creation_allowed": False,
            "telegram_send_allowed": False,
            "production_write_allowed": False,
            "paid_external_service_allowed": False,
            "secret_read_allowed": False,
            "host_probe_allowed": False,
            "npm_audit_allowed": False,
        },
    }


def _source_snapshot(snapshot_id: str, freshness_status: str) -> dict:
    return {
        "snapshot_id": snapshot_id,
        "source_ref": f"docs/evaluations/{snapshot_id}.json",
        "source_schema_version": f"{snapshot_id}_v1",
        "generated_at": "2026-06-04T00:00:00+08:00",
        "freshness_status": freshness_status,
        "evidence_status": "ready",
        "next_action": "review",
    }


def _candidate(candidate_id: str, domain: str, owner_action: str) -> dict:
    return {
        "candidate_id": candidate_id,
        "domain": domain,
        "severity": "high",
        "status": "action_required",
        "owner_agent": "openclaw",
        "summary": candidate_id,
        "evidence_refs": ["docs/evaluations/source.json"],
        "next_owner_action": owner_action,
    }


def _owner_action(action_id: str, owner_agent: str) -> dict:
    return {
        "action_id": action_id,
        "priority": "P2",
        "owner_agent": owner_agent,
        "approval_gate": "human_review_required",
        "summary": action_id,
        "blocked_until": "Owner Gate",
    }
