from __future__ import annotations

import json
import shutil
from pathlib import Path

import pytest

from src.services.github_target_private_backup_evidence_gate import (
    load_latest_github_target_private_backup_evidence_gate,
)
from src.services.snapshot_paths import default_security_dir


def test_load_github_target_private_backup_evidence_gate_from_committed_snapshots():
    snapshot = load_latest_github_target_private_backup_evidence_gate()

    assert snapshot["schema_version"] == "github_target_private_backup_evidence_gate_v1"
    assert snapshot["mode"] == "read_only_private_backup_evidence_gate"
    assert snapshot["status"] == "blocked_public_visibility_and_safe_credential_evidence_required"
    assert snapshot["summary"]["target_decision_count"] == 10
    assert snapshot["summary"]["approval_required_target_count"] == 9
    assert snapshot["summary"]["private_backup_verified_count"] == 0
    assert snapshot["summary"]["blocked_target_count"] == 9
    assert snapshot["summary"]["public_repo_allowed"] is False
    assert snapshot["summary"]["repo_creation_authorized"] is False
    assert snapshot["summary"]["visibility_change_authorized"] is False
    assert snapshot["summary"]["refs_sync_authorized"] is False
    assert snapshot["summary"]["secret_value_collection_allowed"] is False
    assert snapshot["operation_boundaries"]["read_only_api_allowed"] is True
    assert snapshot["operation_boundaries"]["repo_creation_allowed"] is False
    assert snapshot["operation_boundaries"]["visibility_change_allowed"] is False
    assert snapshot["operation_boundaries"]["refs_sync_allowed"] is False
    assert snapshot["operation_boundaries"]["secret_value_collection_allowed"] is False

    targets = {target["github_repo"]: target for target in snapshot["targets"]}
    assert targets["owenhytsai/awoooi"]["visibility_evidence_status"] == (
        "blocked_public_probe_visible_private_evidence_required"
    )
    assert targets["owenhytsai/ewoooc"]["visibility_evidence_status"] == (
        "blocked_private_or_absent_not_verified"
    )
    assert targets["nexu-io/open-design"]["visibility_evidence_status"] == (
        "external_scope_not_backup_target"
    )


def test_github_target_private_backup_gate_rejects_runtime_authorization(tmp_path):
    _copy_security_snapshots(tmp_path)
    owner_response_path = tmp_path / "github-target-owner-decision-response.snapshot.json"
    owner_response = json.loads(owner_response_path.read_text(encoding="utf-8"))
    owner_response["summary"]["repo_creation_authorized"] = True
    owner_response_path.write_text(json.dumps(owner_response), encoding="utf-8")

    with pytest.raises(ValueError, match="boundary flags"):
        load_latest_github_target_private_backup_evidence_gate(tmp_path)


def test_github_target_private_backup_gate_requires_decision_rollup_consistency(tmp_path):
    _copy_security_snapshots(tmp_path)
    decision_path = tmp_path / "github-target-decision.snapshot.json"
    decision = json.loads(decision_path.read_text(encoding="utf-8"))
    decision["decision_count"] = 999
    decision_path.write_text(json.dumps(decision), encoding="utf-8")

    with pytest.raises(ValueError, match="decision_count"):
        load_latest_github_target_private_backup_evidence_gate(tmp_path)


def _copy_security_snapshots(tmp_path: Path) -> None:
    source_dir = default_security_dir(Path(__file__))
    for filename in (
        "github-target-decision.snapshot.json",
        "github-target-owner-decision-response.snapshot.json",
        "github-target-repo-approval-package.snapshot.json",
        "github-target-probe.snapshot.json",
    ):
        shutil.copy(source_dir / filename, tmp_path / filename)
