"""P0-003 Gitea-only private inventory scorecard readback.

This loader promotes the committed Gitea private inventory scorecard into a
stable API contract. It does not call Gitea or GitHub, does not collect token
values, and does not write repository refs or workflow state.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from src.services.snapshot_paths import default_operations_dir

_DEFAULT_OPERATIONS_DIR = default_operations_dir(Path(__file__))
_SCORECARD_FILE = "awoooi-gitea-private-inventory-p0-scorecard.snapshot.json"
_SOURCE_SCHEMA_VERSION = "awoooi_gitea_private_inventory_p0_scorecard_v1"
_API_SCHEMA_VERSION = "gitea_private_inventory_p0_scorecard_readback_v1"
_SINGLE_PREFLIGHT_INTAKE_SCHEMA_VERSION = (
    "gitea_authenticated_inventory_single_preflight_intake_v1"
)
_PAYLOAD_SCHEMA_VERSION = "gitea_repo_inventory_v1"
_ACCEPTED_VISIBILITY_SCOPES = ("authenticated", "admin_export")
_REQUIRED_REDACTION_ATTESTATIONS = (
    "no_token_value",
    "no_write_token",
    "no_webhook_secret",
    "no_deploy_key_private_key",
    "no_runner_registration_token",
    "no_cookie_or_session",
    "no_gitea_db_dump",
    "no_git_object_pack",
)


def load_latest_gitea_private_inventory_p0_scorecard(
    operations_dir: Path | None = None,
) -> dict[str, Any]:
    """Load and validate the committed P0-003 Gitea-only scorecard."""
    directory = operations_dir or _DEFAULT_OPERATIONS_DIR
    path = directory / _SCORECARD_FILE
    with path.open(encoding="utf-8") as handle:
        scorecard = json.load(handle)

    if not isinstance(scorecard, dict):
        raise ValueError(f"{path}: expected JSON object")
    _require_source_scorecard(scorecard, str(path))
    payload = _build_payload(scorecard, path)
    _require_operation_boundaries(payload, str(path))
    _require_rollup_consistency(payload, str(path))
    _require_single_preflight_intake(payload, str(path))
    _require_controlled_closeout_receipt(payload, str(path))
    return payload


def _build_payload(scorecard: dict[str, Any], path: Path) -> dict[str, Any]:
    gitea_inventory = _dict(scorecard.get("gitea_inventory"))
    import_acceptance = _dict(scorecard.get("authenticated_import_acceptance"))
    payload_validation = _dict(scorecard.get("authenticated_payload_validation"))
    coverage_attestation = _dict(scorecard.get("coverage_attestation"))
    owner_response_validation = _dict(scorecard.get("owner_response_validation"))
    controlled_closeout_receipt = _dict(scorecard.get("controlled_closeout_receipt"))
    product_coverage = _dict(scorecard.get("product_row_coverage"))
    active_blockers = _strings(scorecard.get("active_blockers"))
    exit_criteria = _strings(scorecard.get("exit_criteria"))
    met_criteria = _met_exit_criteria(scorecard, gitea_inventory, product_coverage)
    review_readiness_percent = _percent(
        (len(met_criteria) / max(len(exit_criteria), 1)) * 100
    )
    public_repo_floor = max(4, _int(gitea_inventory.get("repo_count")))
    single_preflight_intake = _build_single_preflight_intake(
        generated_at=scorecard.get("generated_at"),
        public_repo_floor=public_repo_floor,
        owner_response_validation=owner_response_validation,
    )

    return {
        "schema_version": _API_SCHEMA_VERSION,
        "generated_at": str(scorecard.get("generated_at") or ""),
        "priority": "P0-003",
        "scope": "gitea_private_inventory_p0_scorecard",
        "status": str(scorecard.get("status") or "unknown"),
        "readback": {
            "workplan_id": str(scorecard.get("workplan_id") or "P0-003"),
            "workplan_title": "取得 Gitea private inventory 權限",
            "source_scorecard_ref": f"docs/operations/{path.name}",
            "source_control_authority": str(
                scorecard.get("source_control_authority") or "gitea"
            ),
            "private_inventory_source": str(
                scorecard.get("private_inventory_source") or "gitea"
            ),
            "safe_next_step": str(scorecard.get("safe_next_step") or ""),
        },
        "gitea_inventory": gitea_inventory,
        "authenticated_import_acceptance": import_acceptance,
        "authenticated_payload_validation": payload_validation,
        "authenticated_inventory_single_preflight_intake_ready": True,
        "authenticated_inventory_payload_skeleton_repo_count_floor": public_repo_floor,
        "authenticated_inventory_required_redaction_attestation_count": len(
            _REQUIRED_REDACTION_ATTESTATIONS
        ),
        "authenticated_inventory_single_preflight_intake": single_preflight_intake,
        "coverage_attestation": coverage_attestation,
        "owner_response_validation": owner_response_validation,
        "controlled_closeout_receipt": controlled_closeout_receipt,
        "product_row_coverage": product_coverage,
        "active_blockers": active_blockers,
        "exit_criteria": exit_criteria,
        "met_exit_criteria": met_criteria,
        "rollups": {
            "active_blocker_count": len(active_blockers),
            "review_readiness_percent": review_readiness_percent,
            "gitea_repo_inventory_status": str(
                gitea_inventory.get("status") or "unknown"
            ),
            "gitea_visibility_scope": str(
                gitea_inventory.get("visibility_scope") or "unknown"
            ),
            "gitea_public_repo_count": _int(gitea_inventory.get("repo_count")),
            "accepted_inventory_payload_count": _int(
                import_acceptance.get("accepted_payload_count")
            ),
            "authenticated_payload_validation_status": str(
                payload_validation.get("status") or "unknown"
            ),
            "authenticated_payload_validation_accepted_count": _int(
                payload_validation.get("accepted_payload_count")
            ),
            "authenticated_payload_validation_blocker_count": _int(
                payload_validation.get("blocker_count")
            ),
            "authenticated_inventory_single_preflight_intake_ready_count": 1,
            "authenticated_inventory_payload_skeleton_repo_count_floor": public_repo_floor,
            "authenticated_inventory_required_redaction_attestation_count": len(
                _REQUIRED_REDACTION_ATTESTATIONS
            ),
            "owner_coverage_attestation_received_count": _int(
                coverage_attestation.get("received_attestation_count")
            ),
            "owner_coverage_attestation_accepted_count": _int(
                coverage_attestation.get("accepted_attestation_count")
            ),
            "owner_response_validation_received_count": _int(
                owner_response_validation.get("received_response_count")
            ),
            "owner_response_validation_accepted_count": _int(
                owner_response_validation.get("accepted_response_count")
            ),
            "owner_response_validation_rejected_count": _int(
                owner_response_validation.get("rejected_response_count")
            ),
            "owner_response_validation_template_count": _int(
                owner_response_validation.get("response_template_count")
            ),
            "controlled_closeout_status": str(
                controlled_closeout_receipt.get("status") or ""
            ),
            "controlled_closeout_paired_receipt_count": _int(
                _dict(controlled_closeout_receipt.get("result")).get(
                    "paired_receipt_count"
                )
            ),
            "controlled_closeout_redacted_receipt_writeback_ready_count": _int(
                _dict(controlled_closeout_receipt.get("result")).get(
                    "redacted_receipt_writeback_ready_count"
                )
            ),
            "controlled_closeout_projected_active_blocker_count": _int(
                _dict(controlled_closeout_receipt.get("result")).get(
                    "projected_active_blocker_count"
                )
            ),
            "owner_response_validation_guard_result": str(
                owner_response_validation.get("latest_local_validation_result") or ""
            ),
            "next_owner_response_validation_lane_id": str(
                owner_response_validation.get("next_collection_candidate_lane_id")
                or ""
            ),
            "expected_product_count": _int(
                product_coverage.get("expected_product_count")
            ),
            "present_product_row_count": _int(
                product_coverage.get("present_product_row_count")
            ),
            "missing_product_row_count": _int(
                product_coverage.get("missing_product_row_count")
            ),
            "ready_product_count": _int(product_coverage.get("ready_product_count")),
            "blocked_product_count": _int(
                product_coverage.get("blocked_product_count")
            ),
            "internal_or_authenticated_inventory_required_count": _int(
                product_coverage.get(
                    "internal_or_authenticated_inventory_required_count"
                )
            ),
            "all_active_product_repos_have_gitea_owner_readiness_row": (
                product_coverage.get(
                    "all_active_product_repos_have_gitea_owner_readiness_row"
                )
                is True
            ),
            "github_lane_excluded_from_p0_blocker_count": (
                scorecard.get("github_lane_excluded_from_p0_blocker_count")
                is True
            ),
            "github_api_used": scorecard.get("github_api_used") is True,
            "github_cli_used": scorecard.get("github_cli_used") is True,
            "github_primary_switch_authorized": (
                scorecard.get("github_primary_switch_authorized") is True
            ),
        },
        "operation_boundaries": {
            "read_only_api_allowed": True,
            "gitea_api_write_allowed": False,
            "gitea_repo_creation_allowed": False,
            "gitea_refs_sync_allowed": False,
            "gitea_visibility_change_allowed": False,
            "gitea_workflow_trigger_allowed": False,
            "authenticated_inventory_import_execution_allowed": False,
            "owner_attestation_write_allowed": False,
            "token_value_collection_allowed": False,
            "secret_value_collection_allowed": False,
            "github_api_allowed": False,
            "github_cli_allowed": False,
            "github_repo_creation_allowed": False,
            "github_refs_sync_allowed": False,
            "github_primary_switch_allowed": False,
            "raw_session_or_sqlite_read_allowed": False,
        },
        "github_retired_context": {
            "status": str(scorecard.get("github_status") or "stopped_retired_do_not_use"),
            "excluded_from_active_p0_blocker_math": (
                scorecard.get("github_lane_excluded_from_p0_blocker_count")
                is True
            ),
            "api_used": scorecard.get("github_api_used") is True,
            "cli_used": scorecard.get("github_cli_used") is True,
            "primary_switch_authorized": (
                scorecard.get("github_primary_switch_authorized") is True
            ),
        },
    }


def _build_single_preflight_intake(
    *,
    generated_at: Any,
    public_repo_floor: int,
    owner_response_validation: dict[str, Any],
) -> dict[str, Any]:
    return {
        "schema_version": _SINGLE_PREFLIGHT_INTAKE_SCHEMA_VERSION,
        "generated_at": generated_at,
        "workplan_id": "P0-003",
        "status": "waiting_for_redacted_authenticated_or_admin_export_inventory_payload",
        "payload_schema_version": _PAYLOAD_SCHEMA_VERSION,
        "accepted_visibility_scopes": list(_ACCEPTED_VISIBILITY_SCOPES),
        "minimum_repo_count": public_repo_floor,
        "required_top_level_fields": [
            "schema_version",
            "status=ok",
            "visibility_scope=authenticated|admin_export",
            "repo_count",
            "repos",
            "coverage_gap_explanation",
            "redaction_attestation",
        ],
        "required_repo_fields": [
            "full_name",
            "name",
            "owner",
            "private",
            "archived",
            "empty",
            "default_branch",
            "clone_url_redacted",
            "ssh_url_redacted",
        ],
        "required_redaction_attestations": list(_REQUIRED_REDACTION_ATTESTATIONS),
        "payload_skeleton": {
            "schema_version": _PAYLOAD_SCHEMA_VERSION,
            "status": "ok",
            "visibility_scope": "admin_export",
            "repo_count": "<redacted_repo_count_at_or_above_public_floor>",
            "coverage_gap_explanation": "coverage_gap_explanation_here",
            "repos": [
                {
                    "full_name": "owner/repo-name",
                    "name": "repo-name",
                    "owner": {"login": "owner"},
                    "private": True,
                    "archived": False,
                    "empty": False,
                    "default_branch": "main",
                    "clone_url_redacted": "https://gitea.example/owner/repo-name.git",
                    "ssh_url_redacted": "ssh://git@gitea.example/owner/repo-name.git",
                }
            ],
            "redaction_attestation": {
                key: "confirm_true_without_secret_values_here"
                for key in _REQUIRED_REDACTION_ATTESTATIONS
            },
            "repo_write_allowed": False,
            "refs_sync_allowed": False,
            "github_primary_switch_authorized": False,
            "runtime_execution_authorized": False,
        },
        "single_preflight_command": (
            "python3 scripts/security/gitea-authenticated-inventory-payload-validator.py "
            "--input <redacted-authenticated-or-admin-export.json> "
            "--output <validation.json>"
        ),
        "owner_response_packet_ref": str(
            owner_response_validation.get("response_packet") or ""
        ),
        "owner_response_lane_id": str(
            owner_response_validation.get("lane_id") or ""
        ),
        "exit_criteria": [
            "validation_status=accepted_for_private_inventory_review_only",
            "accepted_payload_count=1",
            "projected_gitea_repo_inventory_status=ok",
            "projected_gitea_visibility_scope=authenticated|admin_export",
            "token_value_collection_allowed=false",
            "repo_write_allowed=false",
            "refs_sync_allowed=false",
            "github_primary_switch_authorized=false",
        ],
        "operation_boundaries": {
            "payload_persisted": False,
            "gitea_api_called": False,
            "gitea_write_performed": False,
            "repo_write_performed": False,
            "refs_sync_performed": False,
            "github_api_used": False,
            "github_cli_used": False,
            "secret_plaintext_read": False,
            "token_value_collection_allowed": False,
            "runtime_action_performed": False,
            "raw_session_or_sqlite_read_performed": False,
        },
    }


def _require_source_scorecard(payload: dict[str, Any], label: str) -> None:
    if payload.get("schema_version") != _SOURCE_SCHEMA_VERSION:
        raise ValueError(f"{label}: schema_version must be {_SOURCE_SCHEMA_VERSION}")
    if payload.get("source_control_authority") != "gitea":
        raise ValueError(f"{label}: source_control_authority must be gitea")
    if payload.get("private_inventory_source") != "gitea":
        raise ValueError(f"{label}: private_inventory_source must be gitea")
    if payload.get("github_status") != "stopped_retired_do_not_use":
        raise ValueError(f"{label}: github_status must be stopped_retired_do_not_use")
    if payload.get("github_lane_excluded_from_p0_blocker_count") is not True:
        raise ValueError(f"{label}: github lane must be excluded from P0 blocker math")
    if payload.get("github_api_used") is not False:
        raise ValueError(f"{label}: github_api_used must remain false")
    if payload.get("github_cli_used") is not False:
        raise ValueError(f"{label}: github_cli_used must remain false")
    if payload.get("github_primary_switch_authorized") is not False:
        raise ValueError(f"{label}: github_primary_switch_authorized must remain false")

    import_acceptance = _dict(payload.get("authenticated_import_acceptance"))
    if import_acceptance.get("token_value_collection_allowed") is not False:
        raise ValueError(f"{label}: token value collection must remain false")
    if import_acceptance.get("execution_authorized") is not False:
        raise ValueError(f"{label}: import execution must remain false")
    coverage_attestation = _dict(payload.get("coverage_attestation"))
    if coverage_attestation.get("execution_authorized") is not False:
        raise ValueError(f"{label}: attestation write must remain false")
    owner_response_validation = _dict(payload.get("owner_response_validation"))
    if (
        owner_response_validation.get("lane_id")
        != "s4_9_gitea_inventory_owner_attestation_response"
    ):
        raise ValueError(f"{label}: owner response validation lane must be S4.9")
    if (
        owner_response_validation.get("validator_source")
        != "scripts/security/source-control-owner-response-guard.py"
    ):
        raise ValueError(f"{label}: owner response validator source mismatch")
    owner_response_blocked_flags = {
        "runtime_execution_authorized",
        "token_value_collection_allowed",
        "secret_value_collection_allowed",
        "gitea_repo_write_authorized",
        "refs_sync_authorized",
        "github_primary_switch_authorized",
        "action_buttons_allowed",
    }
    owner_response_drift = sorted(
        flag
        for flag in owner_response_blocked_flags
        if owner_response_validation.get(flag) is not False
    )
    if owner_response_drift:
        raise ValueError(
            f"{label}: owner response validation boundaries must remain false: "
            f"{owner_response_drift}"
        )


def _require_operation_boundaries(payload: dict[str, Any], label: str) -> None:
    boundaries = _dict(payload.get("operation_boundaries"))
    if boundaries.get("read_only_api_allowed") is not True:
        raise ValueError(f"{label}: read_only_api_allowed must be true")
    blocked_flags = {
        "gitea_api_write_allowed",
        "gitea_repo_creation_allowed",
        "gitea_refs_sync_allowed",
        "gitea_visibility_change_allowed",
        "gitea_workflow_trigger_allowed",
        "authenticated_inventory_import_execution_allowed",
        "owner_attestation_write_allowed",
        "token_value_collection_allowed",
        "secret_value_collection_allowed",
        "github_api_allowed",
        "github_cli_allowed",
        "github_repo_creation_allowed",
        "github_refs_sync_allowed",
        "github_primary_switch_allowed",
        "raw_session_or_sqlite_read_allowed",
    }
    allowed = sorted(flag for flag in blocked_flags if boundaries.get(flag) is not False)
    if allowed:
        raise ValueError(f"{label}: operation boundaries must remain false: {allowed}")


def _require_rollup_consistency(payload: dict[str, Any], label: str) -> None:
    rollups = _dict(payload.get("rollups"))
    blockers = _strings(payload.get("active_blockers"))
    if rollups.get("active_blocker_count") != len(blockers):
        raise ValueError(f"{label}: active_blocker_count mismatch")
    if rollups.get("github_lane_excluded_from_p0_blocker_count") is not True:
        raise ValueError(f"{label}: github lane exclusion must remain true")
    forbidden_true = [
        "github_api_used",
        "github_cli_used",
        "github_primary_switch_authorized",
    ]
    unexpected_true = [field for field in forbidden_true if rollups.get(field) is True]
    if unexpected_true:
        raise ValueError(f"{label}: GitHub forbidden flags true: {unexpected_true}")
    if rollups.get("missing_product_row_count") != 0:
        raise ValueError(f"{label}: active product readiness rows must remain complete")
    if (
        rollups.get("all_active_product_repos_have_gitea_owner_readiness_row")
        is not True
    ):
        raise ValueError(f"{label}: active product owner readiness rows incomplete")
    if (
        rollups.get("next_owner_response_validation_lane_id")
        != "s4_9_gitea_inventory_owner_attestation_response"
    ):
        raise ValueError(f"{label}: next owner response validation lane mismatch")


def _require_single_preflight_intake(payload: dict[str, Any], label: str) -> None:
    intake = _dict(payload.get("authenticated_inventory_single_preflight_intake"))
    if intake.get("schema_version") != _SINGLE_PREFLIGHT_INTAKE_SCHEMA_VERSION:
        raise ValueError(f"{label}: single preflight intake schema mismatch")
    if intake.get("payload_schema_version") != _PAYLOAD_SCHEMA_VERSION:
        raise ValueError(f"{label}: payload schema version mismatch")
    if intake.get("accepted_visibility_scopes") != list(_ACCEPTED_VISIBILITY_SCOPES):
        raise ValueError(f"{label}: accepted visibility scopes mismatch")
    if intake.get("minimum_repo_count") != payload.get(
        "authenticated_inventory_payload_skeleton_repo_count_floor"
    ):
        raise ValueError(f"{label}: minimum repo count mismatch")
    if intake.get("required_redaction_attestations") != list(
        _REQUIRED_REDACTION_ATTESTATIONS
    ):
        raise ValueError(f"{label}: redaction attestation order mismatch")
    skeleton = _dict(intake.get("payload_skeleton"))
    if skeleton.get("repo_write_allowed") is not False:
        raise ValueError(f"{label}: skeleton repo write must remain false")
    if skeleton.get("refs_sync_allowed") is not False:
        raise ValueError(f"{label}: skeleton refs sync must remain false")
    if skeleton.get("github_primary_switch_authorized") is not False:
        raise ValueError(f"{label}: skeleton github switch must remain false")
    if skeleton.get("runtime_execution_authorized") is not False:
        raise ValueError(f"{label}: skeleton runtime execution must remain false")
    boundaries = _dict(intake.get("operation_boundaries"))
    blocked_flags = {
        "payload_persisted",
        "gitea_api_called",
        "gitea_write_performed",
        "repo_write_performed",
        "refs_sync_performed",
        "github_api_used",
        "github_cli_used",
        "secret_plaintext_read",
        "token_value_collection_allowed",
        "runtime_action_performed",
        "raw_session_or_sqlite_read_performed",
    }
    open_flags = sorted(flag for flag in blocked_flags if boundaries.get(flag) is not False)
    if open_flags:
        raise ValueError(f"{label}: single preflight boundaries opened: {open_flags}")


def _require_controlled_closeout_receipt(
    payload: dict[str, Any], label: str
) -> None:
    receipt = _dict(payload.get("controlled_closeout_receipt"))
    if not receipt:
        return
    if receipt.get("schema_version") != "gitea_private_inventory_controlled_closeout_receipt_v1":
        raise ValueError(f"{label}: controlled closeout receipt schema mismatch")
    if receipt.get("status") != "ready_for_p0_003_controlled_closeout":
        raise ValueError(f"{label}: controlled closeout receipt status mismatch")
    result = _dict(receipt.get("result"))
    if _int(result.get("authenticated_inventory_payload_accepted_count")) < 1:
        raise ValueError(f"{label}: closeout inventory receipt missing")
    if _int(result.get("owner_coverage_attestation_accepted_count")) < 1:
        raise ValueError(f"{label}: closeout owner attestation receipt missing")
    if _int(result.get("redacted_receipt_writeback_ready_count")) < 2:
        raise ValueError(f"{label}: closeout writeback receipt incomplete")
    if _int(result.get("projected_active_blocker_count")) != 0:
        raise ValueError(f"{label}: closeout projected blockers must be zero")

    boundaries = _dict(receipt.get("operation_boundaries"))
    if boundaries.get("source_scorecard_written") is not True:
        raise ValueError(f"{label}: closeout source scorecard writeback missing")
    blocked_flags = {
        "payload_persisted",
        "gitea_api_called",
        "gitea_write_performed",
        "repo_write_performed",
        "refs_sync_performed",
        "github_api_used",
        "github_cli_used",
        "secret_plaintext_read",
        "token_value_collection_allowed",
        "runtime_action_performed",
        "raw_session_or_sqlite_read_performed",
    }
    open_flags = sorted(flag for flag in blocked_flags if boundaries.get(flag) is not False)
    if open_flags:
        raise ValueError(f"{label}: closeout boundaries opened: {open_flags}")


def _met_exit_criteria(
    scorecard: dict[str, Any],
    gitea_inventory: dict[str, Any],
    product_coverage: dict[str, Any],
) -> list[str]:
    met: list[str] = []
    if scorecard.get("private_inventory_source") == "gitea":
        met.append("private_inventory_source=gitea")
    if scorecard.get("github_lane_excluded_from_p0_blocker_count") is True:
        met.append("github_lane_excluded_from_p0_blocker_count=true")
    if gitea_inventory.get("status") == "ok":
        met.append("gitea_repo_inventory.status=ok")
    if gitea_inventory.get("visibility_scope") in {"authenticated", "admin_export"}:
        met.append("gitea_repo_inventory.visibility_scope in authenticated/admin_export")
    if (
        product_coverage.get("all_active_product_repos_have_gitea_owner_readiness_row")
        is True
    ):
        met.append("all_active_product_repos_have_gitea_owner_readiness_row=true")
    return met


def _dict(value: Any) -> dict[str, Any]:
    return value if isinstance(value, dict) else {}


def _strings(value: Any) -> list[str]:
    if not isinstance(value, list):
        return []
    return [str(item) for item in value if item is not None]


def _int(value: Any) -> int:
    if isinstance(value, bool):
        return int(value)
    if isinstance(value, int | float):
        return int(value)
    return 0


def _percent(value: Any) -> int:
    return max(0, min(100, round(float(value or 0))))
