from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path


ROOT = Path(__file__).resolve().parents[3]
SCRIPT = ROOT / "scripts" / "security" / "gitea-private-inventory-p0-scorecard.py"


def load_scorecard() -> dict:
    result = subprocess.run(
        [sys.executable, str(SCRIPT), "--generated-at", "2026-06-29T14:12:00+08:00"],
        text=True,
        capture_output=True,
        check=True,
    )
    return json.loads(result.stdout)


def test_scorecard_excludes_github_from_p0_blocker_math() -> None:
    scorecard = load_scorecard()

    assert scorecard["schema_version"] == "awoooi_gitea_private_inventory_p0_scorecard_v1"
    assert scorecard["workplan_id"] == "P0-003"
    assert scorecard["source_control_authority"] == "gitea"
    assert scorecard["private_inventory_source"] == "gitea"
    assert scorecard["github_status"] == "stopped_retired_do_not_use"
    assert scorecard["github_lane_excluded_from_p0_blocker_count"] is True
    assert scorecard["github_api_used"] is False
    assert scorecard["github_cli_used"] is False
    assert scorecard["github_primary_switch_authorized"] is False
    assert not any("github" in blocker.lower() for blocker in scorecard["active_blockers"])


def test_scorecard_commits_controlled_closeout_receipt() -> None:
    scorecard = load_scorecard()

    assert scorecard["status"] == "closed_gitea_private_inventory_controlled_closeout"
    assert scorecard["gitea_inventory"]["status"] == "ok"
    assert scorecard["gitea_inventory"]["visibility_scope"] == "admin_export"
    assert scorecard["gitea_inventory"]["repo_count"] == 4
    assert {
        "wooo/awoooi",
        "wooo/ewoooc",
        "wooo/agent-bounty-protocol",
        "wooo/2026FIFAWorldCup",
    } <= set(scorecard["gitea_inventory"]["public_repos"])
    assert scorecard["authenticated_import_acceptance"]["accepted_payload_count"] == 1
    assert (
        scorecard["authenticated_payload_validation"]["status"]
        == "accepted_for_private_inventory_review_only"
    )
    assert scorecard["authenticated_payload_validation"]["accepted_payload_count"] == 1
    assert scorecard["authenticated_payload_validation"]["blocker_count"] == 0
    assert (
        scorecard["authenticated_payload_validation"]["validator_source"]
        == "scripts/security/gitea-authenticated-inventory-payload-validator.py"
    )
    assert scorecard["coverage_attestation"]["received_attestation_count"] == 1
    assert scorecard["coverage_attestation"]["accepted_attestation_count"] == 1
    assert (
        scorecard["owner_response_validation"]["lane_id"]
        == "s4_9_gitea_inventory_owner_attestation_response"
    )
    assert scorecard["owner_response_validation"]["response_template_count"] == 5
    assert scorecard["owner_response_validation"]["received_response_count"] == 5
    assert scorecard["owner_response_validation"]["accepted_response_count"] == 5
    assert scorecard["owner_response_validation"]["next_collection_candidate_status"] == "complete"
    assert (
        scorecard["owner_response_validation"]["latest_local_validation_result"]
        == "SOURCE_CONTROL_OWNER_RESPONSE_GUARD_OK"
    )
    assert (
        scorecard["owner_response_validation"]["validator_source"]
        == "scripts/security/source-control-owner-response-guard.py"
    )
    assert scorecard["owner_response_validation"]["runtime_execution_authorized"] is False
    assert scorecard["owner_response_validation"]["gitea_repo_write_authorized"] is False
    assert scorecard["owner_response_validation"]["refs_sync_authorized"] is False
    assert scorecard["active_blockers"] == []
    assert (
        scorecard["controlled_closeout_receipt"]["status"]
        == "ready_for_p0_003_controlled_closeout"
    )
    assert (
        scorecard["controlled_closeout_receipt"]["operation_boundaries"][
            "source_scorecard_written"
        ]
        is True
    )
    assert (
        scorecard["controlled_closeout_receipt"]["operation_boundaries"][
            "gitea_api_called"
        ]
        is False
    )
    assert (
        scorecard["controlled_closeout_receipt"]["operation_boundaries"][
            "runtime_action_performed"
        ]
        is False
    )


def test_scorecard_keeps_all_active_product_rows_visible() -> None:
    scorecard = load_scorecard()
    coverage = scorecard["product_row_coverage"]

    assert coverage["expected_product_count"] == 11
    assert coverage["present_product_row_count"] == 11
    assert coverage["missing_product_row_count"] == 0
    assert coverage["ready_product_count"] == 3
    assert coverage["blocked_product_count"] == 8
    assert coverage["all_active_product_repos_have_gitea_owner_readiness_row"] is True

    product_ids = {row["product_id"] for row in scorecard["product_rows"]}
    assert {"awoooi", "momo-pro", "awooogo", "bitan-pharmacy", "tsenyang-website"} <= product_ids
