from __future__ import annotations

import json

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from src.api.v1.agents import router
from src.services.gitea_authenticated_inventory_payload_validation import (
    validate_gitea_authenticated_inventory_payload,
)
from src.services.gitea_owner_coverage_attestation_validation import (
    validate_gitea_owner_coverage_attestation,
)
from src.services.gitea_private_inventory_closeout_validation import (
    validate_gitea_private_inventory_controlled_closeout,
)
from src.services.gitea_private_inventory_p0_scorecard import (
    load_latest_gitea_private_inventory_p0_scorecard,
)


def test_gitea_private_inventory_p0_scorecard_reports_committed_closeout():
    payload = load_latest_gitea_private_inventory_p0_scorecard()

    assert payload["schema_version"] == "gitea_private_inventory_p0_scorecard_readback_v1"
    assert payload["priority"] == "P0-003"
    assert payload["readback"]["source_control_authority"] == "gitea"
    assert payload["readback"]["private_inventory_source"] == "gitea"
    assert payload["status"] == "closed_gitea_private_inventory_controlled_closeout"
    assert payload["rollups"]["active_blocker_count"] == 0
    assert payload["rollups"]["review_readiness_percent"] == 100
    assert payload["rollups"]["gitea_repo_inventory_status"] == "ok"
    assert payload["rollups"]["gitea_visibility_scope"] == "admin_export"
    assert payload["rollups"]["accepted_inventory_payload_count"] == 1
    assert (
        payload["rollups"]["authenticated_payload_validation_status"]
        == "accepted_for_private_inventory_review_only"
    )
    assert payload["rollups"]["authenticated_payload_validation_accepted_count"] == 1
    assert payload["rollups"]["authenticated_payload_validation_blocker_count"] == 0
    assert (
        payload["rollups"][
            "authenticated_inventory_single_preflight_intake_ready_count"
        ]
        == 1
    )
    assert (
        payload["rollups"][
            "authenticated_inventory_required_redaction_attestation_count"
        ]
        == 8
    )
    assert payload["authenticated_inventory_single_preflight_intake_ready"] is True
    assert (
        payload["authenticated_inventory_payload_skeleton_repo_count_floor"]
        == 4
    )
    assert payload["rollups"]["owner_coverage_attestation_received_count"] == 1
    assert payload["rollups"]["owner_coverage_attestation_accepted_count"] == 1
    assert payload["rollups"]["owner_response_validation_received_count"] == 5
    assert payload["rollups"]["owner_response_validation_accepted_count"] == 5
    assert payload["rollups"]["owner_response_validation_template_count"] == 5
    assert (
        payload["rollups"]["owner_response_validation_guard_result"]
        == "SOURCE_CONTROL_OWNER_RESPONSE_GUARD_OK"
    )
    assert (
        payload["rollups"]["next_owner_response_validation_lane_id"]
        == "s4_9_gitea_inventory_owner_attestation_response"
    )
    assert payload["rollups"]["expected_product_count"] == 11
    assert payload["rollups"]["present_product_row_count"] == 11
    assert payload["rollups"]["missing_product_row_count"] == 0
    assert payload["rollups"]["all_active_product_repos_have_gitea_owner_readiness_row"] is True
    assert payload["rollups"]["github_lane_excluded_from_p0_blocker_count"] is True
    assert payload["github_retired_context"]["status"] == "stopped_retired_do_not_use"
    assert payload["github_retired_context"]["excluded_from_active_p0_blocker_math"] is True
    assert (
        payload["authenticated_payload_validation"]["status"]
        == "accepted_for_private_inventory_review_only"
    )
    assert payload["active_blockers"] == []
    assert (
        payload["controlled_closeout_receipt"]["status"]
        == "ready_for_p0_003_controlled_closeout"
    )
    assert payload["rollups"]["controlled_closeout_paired_receipt_count"] == 2
    assert (
        payload["rollups"][
            "controlled_closeout_redacted_receipt_writeback_ready_count"
        ]
        == 2
    )
    assert payload["rollups"]["controlled_closeout_projected_active_blocker_count"] == 0
    assert (
        payload["controlled_closeout_receipt"]["operation_boundaries"][
            "source_scorecard_written"
        ]
        is True
    )
    assert (
        payload["controlled_closeout_receipt"]["operation_boundaries"][
            "gitea_api_called"
        ]
        is False
    )
    assert (
        payload["controlled_closeout_receipt"]["operation_boundaries"][
            "runtime_action_performed"
        ]
        is False
    )


def test_gitea_private_inventory_p0_scorecard_exposes_single_preflight_intake():
    payload = load_latest_gitea_private_inventory_p0_scorecard()

    intake = payload["authenticated_inventory_single_preflight_intake"]
    assert (
        intake["schema_version"]
        == "gitea_authenticated_inventory_single_preflight_intake_v1"
    )
    assert intake["workplan_id"] == "P0-003"
    assert intake["payload_schema_version"] == "gitea_repo_inventory_v1"
    assert intake["accepted_visibility_scopes"] == ["authenticated", "admin_export"]
    assert intake["minimum_repo_count"] == 4
    assert len(intake["required_redaction_attestations"]) == 8
    assert "no_token_value" in intake["required_redaction_attestations"]
    assert "no_gitea_db_dump" in intake["required_redaction_attestations"]
    assert "gitea-authenticated-inventory-payload-validator.py" in (
        intake["single_preflight_command"]
    )
    assert (
        intake["owner_response_lane_id"]
        == "s4_9_gitea_inventory_owner_attestation_response"
    )
    assert (
        intake["owner_response_packet_ref"]
        == "docs/security/gitea-inventory-owner-attestation-response.snapshot.json"
    )
    assert "accepted_payload_count=1" in intake["exit_criteria"]

    skeleton = intake["payload_skeleton"]
    assert skeleton["schema_version"] == "gitea_repo_inventory_v1"
    assert skeleton["status"] == "ok"
    assert skeleton["visibility_scope"] == "admin_export"
    assert skeleton["repo_write_allowed"] is False
    assert skeleton["refs_sync_allowed"] is False
    assert skeleton["github_primary_switch_authorized"] is False
    assert skeleton["runtime_execution_authorized"] is False
    assert len(skeleton["redaction_attestation"]) == 8
    assert intake["operation_boundaries"]["payload_persisted"] is False
    assert intake["operation_boundaries"]["gitea_api_called"] is False
    assert intake["operation_boundaries"]["token_value_collection_allowed"] is False
    assert intake["operation_boundaries"]["github_api_used"] is False
    assert intake["operation_boundaries"]["runtime_action_performed"] is False


def test_gitea_private_inventory_p0_scorecard_endpoint_returns_readback():
    app = FastAPI()
    app.include_router(router, prefix="/api/v1")
    client = TestClient(app)

    response = client.get("/api/v1/agents/gitea-private-inventory-p0-scorecard")

    assert response.status_code == 200
    data = response.json()
    assert data["priority"] == "P0-003"
    assert data["status"] == "closed_gitea_private_inventory_controlled_closeout"
    assert data["rollups"]["active_blocker_count"] == 0
    assert data["rollups"]["review_readiness_percent"] == 100
    assert data["owner_response_validation"]["received_response_count"] == 5
    assert data["owner_response_validation"]["accepted_response_count"] == 5
    assert (
        data["owner_response_validation"]["validator_source"]
        == "scripts/security/source-control-owner-response-guard.py"
    )
    assert data["operation_boundaries"]["read_only_api_allowed"] is True
    assert data["operation_boundaries"]["gitea_api_write_allowed"] is False
    assert data["operation_boundaries"]["gitea_repo_creation_allowed"] is False
    assert data["operation_boundaries"]["gitea_refs_sync_allowed"] is False
    assert data["operation_boundaries"]["gitea_workflow_trigger_allowed"] is False
    assert data["operation_boundaries"]["token_value_collection_allowed"] is False
    assert data["operation_boundaries"]["secret_value_collection_allowed"] is False
    assert data["operation_boundaries"]["github_api_allowed"] is False
    assert data["operation_boundaries"]["github_cli_allowed"] is False
    assert data["operation_boundaries"]["raw_session_or_sqlite_read_allowed"] is False
    assert data["authenticated_payload_validation"]["accepted_payload_count"] == 1
    assert data["authenticated_inventory_single_preflight_intake_ready"] is True
    assert data["authenticated_inventory_single_preflight_intake"][
        "minimum_repo_count"
    ] == 4
    assert (
        data["controlled_closeout_receipt"]["status"]
        == "ready_for_p0_003_controlled_closeout"
    )
    assert (
        data["controlled_closeout_receipt"]["operation_boundaries"][
            "source_scorecard_written"
        ]
        is True
    )
    assert (
        data["controlled_closeout_receipt"]["operation_boundaries"][
            "repo_write_performed"
        ]
        is False
    )


def test_gitea_authenticated_inventory_payload_validator_accepts_redacted_admin_export():
    payload = validate_gitea_authenticated_inventory_payload(
        _valid_authenticated_inventory_payload(),
        scorecard=_scorecard_readback(),
    )

    assert payload["schema_version"] == "gitea_authenticated_inventory_payload_validation_v1"
    assert payload["status"] == "accepted_for_private_inventory_review_only"
    assert payload["result"]["accepted_payload_count"] == 1
    assert payload["result"]["repo_count"] == 4
    assert payload["result"]["current_active_blocker_count"] == 4
    assert payload["result"]["projected_active_blocker_count"] == 1
    assert payload["result"]["projected_accepted_inventory_payload_count"] == 1
    assert payload["result"]["projected_gitea_repo_inventory_status"] == "ok"
    assert payload["result"]["projected_gitea_visibility_scope"] == "admin_export"
    assert payload["result"]["runtime_gate_count"] == 0
    assert payload["operation_boundaries"]["payload_persisted"] is False
    assert payload["operation_boundaries"]["gitea_api_called"] is False
    assert payload["operation_boundaries"]["repo_write_performed"] is False
    assert payload["operation_boundaries"]["refs_sync_performed"] is False
    assert payload["operation_boundaries"]["github_api_used"] is False
    assert payload["operation_boundaries"]["secret_plaintext_read"] is False
    assert (
        payload["reviewer_readiness"]["status"]
        == "ready_for_owner_coverage_attestation_review"
    )
    assert payload["reviewer_readiness"]["redacted_inventory_receipt_writeback_ready_count"] == 1
    assert payload["reviewer_readiness"]["owner_coverage_attestation_still_required_count"] == 1
    assert payload["reviewer_readiness"]["repo_write_authorized_count"] == 0


def test_gitea_authenticated_inventory_payload_endpoint_validates_without_persisting():
    app = FastAPI()
    app.include_router(router, prefix="/api/v1")
    client = TestClient(app)

    response = client.post(
        "/api/v1/agents/gitea-private-inventory-p0-scorecard/validate-authenticated-inventory-payload",
        json=_valid_authenticated_inventory_payload(),
    )

    assert response.status_code == 200
    data = response.json()
    assert data["status"] == "accepted_for_private_inventory_review_only"
    assert data["result"]["accepted_payload_count"] == 1
    assert data["result"]["projected_active_blocker_count"] == 0
    assert data["reviewer_readiness"]["redacted_inventory_receipt_writeback_ready_count"] == 1
    assert data["operation_boundaries"]["payload_persisted"] is False
    assert data["operation_boundaries"]["gitea_write_performed"] is False
    assert data["operation_boundaries"]["raw_session_or_sqlite_read_performed"] is False


def test_gitea_owner_coverage_attestation_validator_accepts_redacted_response():
    payload = validate_gitea_owner_coverage_attestation(
        _valid_owner_coverage_attestation_payload(),
        scorecard=_scorecard_readback(),
    )

    assert payload["schema_version"] == "gitea_owner_coverage_attestation_validation_v1"
    assert payload["status"] == "accepted_for_owner_coverage_attestation_review_only"
    assert payload["result"]["accepted_attestation_packet_count"] == 1
    assert payload["result"]["required_response_item_count"] == 5
    assert payload["result"]["provided_response_item_count"] == 5
    assert payload["result"]["accepted_response_count"] == 5
    assert payload["result"]["current_active_blocker_count"] == 4
    assert payload["result"]["projected_active_blocker_count"] == 3
    assert (
        payload["result"][
            "projected_active_blocker_count_after_redacted_inventory_receipt_writeback"
        ]
        == 0
    )
    assert payload["result"]["projected_owner_coverage_attestation_accepted_count"] == 1
    assert payload["result"]["runtime_gate_count"] == 0
    assert payload["operation_boundaries"]["payload_persisted"] is False
    assert payload["operation_boundaries"]["gitea_api_called"] is False
    assert payload["operation_boundaries"]["repo_write_performed"] is False
    assert payload["operation_boundaries"]["refs_sync_performed"] is False
    assert payload["operation_boundaries"]["github_api_used"] is False
    assert payload["operation_boundaries"]["secret_plaintext_read"] is False
    assert (
        payload["reviewer_readiness"]["status"]
        == "ready_for_private_inventory_closeout_after_inventory_receipt_writeback"
    )
    assert (
        payload["reviewer_readiness"][
            "redacted_owner_attestation_receipt_writeback_ready_count"
        ]
        == 1
    )
    assert payload["reviewer_readiness"]["repo_write_authorized_count"] == 0


def test_gitea_owner_coverage_attestation_endpoint_validates_without_persisting():
    app = FastAPI()
    app.include_router(router, prefix="/api/v1")
    client = TestClient(app)

    response = client.post(
        "/api/v1/agents/gitea-private-inventory-p0-scorecard/validate-owner-coverage-attestation",
        json=_valid_owner_coverage_attestation_payload(),
    )

    assert response.status_code == 200
    data = response.json()
    assert data["status"] == "accepted_for_owner_coverage_attestation_review_only"
    assert data["result"]["accepted_attestation_packet_count"] == 1
    assert data["result"]["projected_active_blocker_count"] == 0
    assert (
        data["reviewer_readiness"][
            "redacted_owner_attestation_receipt_writeback_ready_count"
        ]
        == 1
    )
    assert data["operation_boundaries"]["payload_persisted"] is False
    assert data["operation_boundaries"]["gitea_write_performed"] is False
    assert data["operation_boundaries"]["raw_session_or_sqlite_read_performed"] is False


def test_gitea_owner_coverage_attestation_validator_quarantines_secret_material():
    payload = _valid_owner_coverage_attestation_payload()
    payload["responses"][0]["evidence_refs"] = [
        "https://gitea.example/wooo/awoooi?token=secret-value"
    ]

    validation = validate_gitea_owner_coverage_attestation(
        payload,
        scorecard=_scorecard_readback(),
    )

    assert validation["status"] == "quarantined_sensitive_payload"
    assert validation["result"]["accepted_attestation_packet_count"] == 0
    assert validation["result"]["sensitive_payload_hit_count"] >= 1
    assert validation["operation_boundaries"]["payload_persisted"] is False


def test_gitea_owner_coverage_attestation_validator_rejects_execution_request():
    payload = _valid_owner_coverage_attestation_payload()
    payload["write_to_gitea"] = True

    validation = validate_gitea_owner_coverage_attestation(
        payload,
        scorecard=_scorecard_readback(),
    )

    assert validation["status"] == "rejected_execution_request"
    assert validation["result"]["accepted_attestation_packet_count"] == 0
    assert validation["result"]["forbidden_true_field_count"] == 1
    assert validation["operation_boundaries"]["repo_write_performed"] is False


def test_gitea_private_inventory_controlled_closeout_accepts_paired_redacted_inputs():
    payload = validate_gitea_private_inventory_controlled_closeout(
        _valid_controlled_closeout_payload(),
        scorecard=_scorecard_readback(),
    )

    assert (
        payload["schema_version"]
        == "gitea_private_inventory_controlled_closeout_validation_v1"
    )
    assert payload["status"] == "ready_for_p0_003_controlled_closeout"
    assert payload["result"]["authenticated_inventory_payload_accepted_count"] == 1
    assert payload["result"]["owner_coverage_attestation_accepted_count"] == 1
    assert payload["result"]["paired_receipt_count"] == 2
    assert payload["result"]["redacted_receipt_writeback_ready_count"] == 2
    assert payload["result"]["current_active_blocker_count"] == 4
    assert payload["result"]["projected_active_blocker_count"] == 0
    assert payload["result"]["runtime_gate_count"] == 0
    assert payload["operation_boundaries"]["payload_persisted"] is False
    assert payload["operation_boundaries"]["source_scorecard_written"] is False
    assert payload["operation_boundaries"]["gitea_api_called"] is False
    assert payload["operation_boundaries"]["repo_write_performed"] is False
    assert payload["operation_boundaries"]["refs_sync_performed"] is False
    assert payload["operation_boundaries"]["github_api_used"] is False
    assert payload["operation_boundaries"]["runtime_action_performed"] is False
    assert (
        payload["reviewer_readiness"]["status"]
        == "ready_for_redacted_receipt_source_writeback"
    )


def test_gitea_private_inventory_controlled_closeout_endpoint_no_persist():
    app = FastAPI()
    app.include_router(router, prefix="/api/v1")
    client = TestClient(app)

    response = client.post(
        "/api/v1/agents/gitea-private-inventory-p0-scorecard/validate-controlled-closeout",
        json=_valid_controlled_closeout_payload(),
    )

    assert response.status_code == 200
    data = response.json()
    assert data["status"] == "ready_for_p0_003_controlled_closeout"
    assert data["result"]["projected_active_blocker_count"] == 0
    assert data["result"]["redacted_receipt_writeback_ready_count"] == 2
    assert data["operation_boundaries"]["payload_persisted"] is False
    assert data["operation_boundaries"]["source_scorecard_written"] is False
    assert data["operation_boundaries"]["raw_session_or_sqlite_read_performed"] is False


def test_gitea_private_inventory_controlled_closeout_blocks_unaccepted_pair():
    packet = _valid_controlled_closeout_payload()
    packet["owner_coverage_attestation"]["responses"][0]["decision"] = "not_allowed"

    validation = validate_gitea_private_inventory_controlled_closeout(
        packet,
        scorecard=_scorecard_readback(),
    )

    assert validation["status"] == "needs_supplement"
    assert validation["result"]["paired_receipt_count"] == 0
    assert validation["result"]["projected_active_blocker_count"] == 4
    assert "owner_coverage_attestation_not_accepted" in validation["closeout_blockers"]
    assert validation["operation_boundaries"]["source_scorecard_written"] is False


def test_gitea_authenticated_inventory_payload_validator_quarantines_secret_material():
    payload = _valid_authenticated_inventory_payload()
    payload["repos"][0]["clone_url_redacted"] = "https://user:password@example.test/repo.git"

    validation = validate_gitea_authenticated_inventory_payload(
        payload,
        scorecard=_scorecard_readback(),
    )

    assert validation["status"] == "quarantined_sensitive_payload"
    assert validation["result"]["accepted_payload_count"] == 0
    assert validation["result"]["sensitive_payload_hit_count"] >= 1
    assert validation["operation_boundaries"]["payload_persisted"] is False


def test_gitea_authenticated_inventory_payload_validator_rejects_execution_request():
    payload = _valid_authenticated_inventory_payload()
    payload["repo_write_allowed"] = True

    validation = validate_gitea_authenticated_inventory_payload(
        payload,
        scorecard=_scorecard_readback(),
    )

    assert validation["status"] == "rejected_execution_request"
    assert validation["result"]["accepted_payload_count"] == 0
    assert validation["result"]["forbidden_true_field_count"] == 1
    assert validation["operation_boundaries"]["repo_write_performed"] is False


def test_gitea_private_inventory_p0_scorecard_rejects_github_reactivation(tmp_path):
    operations_dir = tmp_path / "operations"
    operations_dir.mkdir()
    payload = _scorecard_payload()
    payload["github_lane_excluded_from_p0_blocker_count"] = False
    (operations_dir / "awoooi-gitea-private-inventory-p0-scorecard.snapshot.json").write_text(
        json.dumps(payload),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="github lane"):
        load_latest_gitea_private_inventory_p0_scorecard(operations_dir)


def test_gitea_private_inventory_p0_scorecard_rejects_token_collection(tmp_path):
    operations_dir = tmp_path / "operations"
    operations_dir.mkdir()
    payload = _scorecard_payload()
    payload["authenticated_import_acceptance"]["token_value_collection_allowed"] = True
    (operations_dir / "awoooi-gitea-private-inventory-p0-scorecard.snapshot.json").write_text(
        json.dumps(payload),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="token value collection"):
        load_latest_gitea_private_inventory_p0_scorecard(operations_dir)


def test_gitea_private_inventory_p0_scorecard_rejects_owner_response_runtime_unlock(
    tmp_path,
):
    operations_dir = tmp_path / "operations"
    operations_dir.mkdir()
    payload = _scorecard_payload()
    payload["owner_response_validation"]["runtime_execution_authorized"] = True
    (operations_dir / "awoooi-gitea-private-inventory-p0-scorecard.snapshot.json").write_text(
        json.dumps(payload),
        encoding="utf-8",
    )

    with pytest.raises(ValueError, match="owner response validation boundaries"):
        load_latest_gitea_private_inventory_p0_scorecard(operations_dir)


def _scorecard_payload() -> dict:
    return {
        "schema_version": "awoooi_gitea_private_inventory_p0_scorecard_v1",
        "generated_at": "2026-06-29T14:09:49+08:00",
        "workplan_id": "P0-003",
        "status": "blocked_waiting_gitea_authenticated_or_owner_export_inventory",
        "source_control_authority": "gitea",
        "private_inventory_source": "gitea",
        "github_status": "stopped_retired_do_not_use",
        "github_lane_excluded_from_p0_blocker_count": True,
        "github_api_used": False,
        "github_cli_used": False,
        "github_primary_switch_authorized": False,
        "gitea_inventory": {
            "schema_version": "gitea_repo_inventory_v1",
            "status": "partial",
            "visibility_scope": "public_only",
            "repo_count": 2,
        },
        "authenticated_import_acceptance": {
            "schema_version": "gitea_authenticated_inventory_import_acceptance_v1",
            "status": "draft_waiting_redacted_inventory_payload",
            "accepted_payload_count": 0,
            "token_value_collection_allowed": False,
            "execution_authorized": False,
        },
        "coverage_attestation": {
            "schema_version": "gitea_inventory_coverage_attestation_v1",
            "status": "draft_waiting_owner_attestation",
            "received_attestation_count": 0,
            "accepted_attestation_count": 0,
            "execution_authorized": False,
        },
        "owner_response_validation": {
            "schema_version": "source_control_owner_response_validation_rollup_v1",
            "status": "draft_waiting_owner_responses",
            "rollup_status": "waiting_owner_responses",
            "lane_id": "s4_9_gitea_inventory_owner_attestation_response",
            "source_contract": "gitea_inventory_owner_attestation_response_v1",
            "response_packet": (
                "docs/security/gitea-inventory-owner-attestation-response.snapshot.json"
            ),
            "response_template_count": 5,
            "received_response_count": 0,
            "accepted_response_count": 0,
            "rejected_response_count": 0,
            "next_collection_candidate_lane_id": (
                "s4_9_gitea_inventory_owner_attestation_response"
            ),
            "next_collection_candidate_status": "next_owner_response_required",
            "latest_local_validation_status": "repo_snapshot_guard_pass",
            "latest_local_validation_result": "SOURCE_CONTROL_OWNER_RESPONSE_GUARD_OK",
            "validator_source": "scripts/security/source-control-owner-response-guard.py",
            "runtime_execution_authorized": False,
            "token_value_collection_allowed": False,
            "secret_value_collection_allowed": False,
            "gitea_repo_write_authorized": False,
            "refs_sync_authorized": False,
            "github_primary_switch_authorized": False,
            "action_buttons_allowed": False,
        },
        "product_row_coverage": {
            "expected_product_count": 11,
            "present_product_row_count": 11,
            "missing_product_row_count": 0,
            "ready_product_count": 3,
            "blocked_product_count": 8,
            "internal_or_authenticated_inventory_required_count": 3,
            "all_active_product_repos_have_gitea_owner_readiness_row": True,
        },
        "active_blockers": [
            "gitea_repo_inventory_status_not_ok",
            "gitea_visibility_scope_public_only_or_unknown",
            "gitea_authenticated_inventory_payload_not_accepted",
            "gitea_owner_coverage_attestation_not_received",
        ],
        "exit_criteria": [
            "private_inventory_source=gitea",
            "github_lane_excluded_from_p0_blocker_count=true",
            "gitea_repo_inventory.status=ok",
            "gitea_repo_inventory.visibility_scope in authenticated/admin_export",
            "all_active_product_repos_have_gitea_owner_readiness_row=true",
        ],
        "safe_next_step": (
            "obtain_gitea_authenticated_or_admin_export_redacted_inventory_payload_"
            "then_validate_import_acceptance_and_owner_attestation"
        ),
    }


def _scorecard_readback() -> dict:
    return {
        "status": "blocked_waiting_gitea_authenticated_or_owner_export_inventory",
        "active_blockers": [
            "gitea_repo_inventory_status_not_ok",
            "gitea_visibility_scope_public_only_or_unknown",
            "gitea_authenticated_inventory_payload_not_accepted",
            "gitea_owner_coverage_attestation_not_received",
        ],
        "rollups": {
            "accepted_inventory_payload_count": 0,
            "owner_coverage_attestation_accepted_count": 0,
            "gitea_repo_inventory_status": "partial",
            "gitea_visibility_scope": "public_only",
        },
    }


def _valid_authenticated_inventory_payload() -> dict:
    repos = [
        _repo("wooo/awoooi"),
        _repo("wooo/ewoooc"),
        _repo("wooo/agent-bounty-protocol"),
        _repo("wooo/2026FIFAWorldCup"),
    ]
    return {
        "schema_version": "gitea_repo_inventory_v1",
        "base_url": "https://gitea.wooo.work",
        "org": "wooo",
        "visibility_scope": "admin_export",
        "token_present": False,
        "status": "ok",
        "repo_count": len(repos),
        "repos": repos,
        "coverage_gap_explanation": {
            "public_only_vs_admin_export": "admin export includes all in-scope repos",
            "internal_110_adjacent_scope": "covered by owner scope decision",
            "org_user_endpoint_identity": "wooo namespace owner confirmed",
        },
        "redaction_attestation": {
            "no_token_value": True,
            "no_write_token": True,
            "no_webhook_secret": True,
            "no_deploy_key_private_key": True,
            "no_runner_registration_token": True,
            "no_cookie_or_session": True,
            "no_gitea_db_dump": True,
            "no_git_object_pack": True,
        },
    }


def _valid_owner_coverage_attestation_payload() -> dict:
    return {
        "schema_version": "gitea_inventory_owner_attestation_response_v1",
        "lane_id": "s4_9_gitea_inventory_owner_attestation_response",
        "runtime_execution_authorized": False,
        "token_value_collection_allowed": False,
        "secret_value_collection_allowed": False,
        "gitea_repo_write_authorized": False,
        "refs_sync_authorized": False,
        "github_primary_switch_authorized": False,
        "action_buttons_allowed": False,
        "responses": [
            {
                "attestation_item_id": "public_only_vs_local_gitea_gap",
                "owner_role_or_team": "platform-security-owner",
                "decision": "in_scope",
                "decision_reason": "admin export must cover the public-only gap",
                "affected_repos": ["wooo/awoooi", "wooo/ewoooc"],
                "evidence_refs": [
                    "docs/security/gitea-repo-inventory.snapshot.json",
                    "docs/security/gitea-org-repo-inventory-blocked.snapshot.json",
                ],
                "followup_owner": "platform-security-owner",
            },
            {
                "attestation_item_id": "org_user_endpoint_identity",
                "owner_role_or_team": "platform-security-owner",
                "decision": "in_scope",
                "decision_reason": "wooo namespace is the canonical Gitea scope",
                "canonical_namespace": "wooo",
                "evidence_refs": [
                    "docs/security/gitea-org-repo-inventory-blocked.snapshot.json"
                ],
                "followup_owner": "platform-security-owner",
            },
            {
                "attestation_item_id": "internal_110_adjacent_scope",
                "owner_role_or_team": "platform-security-owner",
                "decision": "in_scope",
                "decision_reason": "internal adjacent source is covered by redacted metadata",
                "affected_sources": ["gitea-ssh-main-redacted", "public-route-redacted"],
                "evidence_refs": [
                    "docs/security/git-remote-refs-bitan-exposure.snapshot.json"
                ],
                "followup_owner": "platform-security-owner",
            },
            {
                "attestation_item_id": "repo_owner_canonical_scope",
                "owner_role_or_team": "platform-security-owner",
                "decision": "in_scope",
                "decision_reason": "repo owner and canonical source remain Gitea-only",
                "repo_owner": "wooo",
                "canonical_source": "gitea",
                "github_target_candidate": "stopped_retired_do_not_use",
                "visibility_review_owner": "platform-security-owner",
                "evidence_refs": [
                    "docs/operations/awoooi-gitea-private-inventory-p0-scorecard.snapshot.json"
                ],
            },
            {
                "attestation_item_id": "legacy_or_inaccessible_repo_disposition",
                "owner_role_or_team": "platform-security-owner",
                "decision": "legacy_archived",
                "decision_reason": "legacy or inaccessible sources stay outside active P0 apply",
                "affected_repos_or_sources": ["legacy-github-mirror-retired"],
                "disposition": "stopped_retired_do_not_use",
                "evidence_refs": [
                    "docs/security/gitea-inventory-owner-attestation-response.snapshot.json"
                ],
                "followup_owner": "platform-security-owner",
            },
        ],
    }


def _valid_controlled_closeout_payload() -> dict:
    return {
        "authenticated_inventory_payload": _valid_authenticated_inventory_payload(),
        "owner_coverage_attestation": _valid_owner_coverage_attestation_payload(),
    }


def _repo(full_name: str) -> dict:
    _, name = full_name.split("/", 1)
    return {
        "gitea_repo": full_name,
        "name": name,
        "owner": "wooo",
        "private": False,
        "empty": False,
        "archived": False,
        "default_branch": "main",
        "clone_url_redacted": f"https://gitea.wooo.work/{full_name}.git",
        "ssh_url_redacted": f"ssh://gitea.wooo.work/{full_name}.git",
        "github_repo_candidate": "",
    }
