"""Gitea workflow runner owner attestation request readback.

Builds a metadata-only request packet from the committed Gitea workflow /
runner health contract. This module never sends the request, calls Gitea,
changes runner labels, registers runners, triggers workflows, or reads secrets.
"""

from __future__ import annotations

from typing import Any

from src.services.gitea_workflow_runner_health import (
    load_latest_gitea_workflow_runner_health,
)

_SCHEMA_VERSION = "gitea_workflow_runner_owner_attestation_request_v1"
_CONTRACT_ID = "ubuntu_latest_gitea_runner_label"
_REQUIRED_FIELDS = [
    "runner_label",
    "actual_runner_mapping_ref",
    "runner_host_alias",
    "executor_scope",
    "capacity_owner",
    "maintenance_window",
    "evidence_ref",
    "no_secret_value_attestation",
    "no_runner_registration_change_attestation",
    "rollback_owner",
    "post_check_owner",
]
_FORBIDDEN_ACTIONS = [
    "workflow_modification",
    "workflow_dispatch",
    "runner_label_change",
    "runner_registration",
    "runner_restart",
    "runner_container_stop",
    "secret_or_runner_token_read",
    "gitea_api_write",
    "github_api",
]


def load_latest_gitea_workflow_runner_owner_attestation_request() -> dict[str, Any]:
    """Return the owner attestation request packet for runner label evidence."""

    health = load_latest_gitea_workflow_runner_health()
    rollups = _dict(health.get("rollups"))
    action_contracts = [
        contract
        for contract in health.get("runner_contracts", [])
        if isinstance(contract, dict)
        and contract.get("contract_id")
        in set(_strings(rollups.get("runner_contracts_requiring_action")))
    ]
    target_contract = next(
        (
            contract
            for contract in action_contracts
            if contract.get("contract_id") == _CONTRACT_ID
        ),
        {},
    )
    workflow_ids = _strings(rollups.get("workflow_ids_requiring_runner_attestation"))
    request_ready = bool(target_contract) and bool(workflow_ids)
    active_blockers = []
    if not request_ready:
        active_blockers.append("runner_attestation_request_source_missing")
    active_blockers.append("owner_attestation_response_not_received")

    return {
        "schema_version": _SCHEMA_VERSION,
        "priority": "P1-002",
        "scope": "gitea_workflow_runner_owner_attestation_request",
        "status": (
            "owner_attestation_request_ready_waiting_response"
            if request_ready
            else "blocked_owner_attestation_request_source_missing"
        ),
        "readback": {
            "workplan_id": "P1-002-GITEA-RUNNER-OWNER-ATTESTATION",
            "source_health_schema_version": health.get("schema_version"),
            "source_health_endpoint": "/api/v1/agents/gitea-workflow-runner-health",
            "contract_id": _CONTRACT_ID,
            "runner_label": _first_string(target_contract.get("runner_labels")),
            "request_packet_id": "gitea_runner_owner_attestation_request::ubuntu_latest",
            "safe_next_step": (
                "collect_redacted_owner_attestation_response_then_validate_no_runner_mutation"
            ),
        },
        "request_packet": {
            "request_template_ready": request_ready,
            "request_sent": False,
            "owner_response_received": False,
            "owner_response_accepted": False,
            "contract_id": _CONTRACT_ID,
            "display_name": str(target_contract.get("display_name") or ""),
            "risk_level": str(target_contract.get("risk_level") or "high"),
            "runner_labels": _strings(target_contract.get("runner_labels")),
            "workflow_ids_requiring_attestation": workflow_ids,
            "required_owner_fields": _REQUIRED_FIELDS,
            "forbidden_actions": _FORBIDDEN_ACTIONS,
            "allowed_response_shape": {
                "redacted_metadata_only": True,
                "evidence_ref_required": True,
                "secret_value_allowed": False,
                "runner_token_allowed": False,
                "authorization_header_allowed": False,
                "raw_runner_config_allowed": False,
            },
            "acceptance_checks": [
                "runner_label_mapping_ref_present",
                "runner_host_alias_present",
                "capacity_owner_present",
                "maintenance_window_present",
                "no_secret_value_attested",
                "no_runner_registration_change_attested",
                "post_check_owner_present",
            ],
            "rejection_rules": [
                "contains_secret_value",
                "contains_runner_token",
                "requests_runner_label_change",
                "requests_runner_registration",
                "requests_workflow_dispatch",
                "missing_evidence_ref",
            ],
        },
        "rollups": {
            "request_template_ready": request_ready,
            "request_packet_count": int(request_ready),
            "workflow_requiring_attestation_count": len(workflow_ids),
            "runner_contracts_requiring_action_count": len(action_contracts),
            "required_owner_field_count": len(_REQUIRED_FIELDS),
            "forbidden_action_count": len(_FORBIDDEN_ACTIONS),
            "owner_response_received_count": 0,
            "owner_response_accepted_count": 0,
            "active_blocker_count": len(active_blockers),
            "runtime_gate_opened": False,
        },
        "active_blockers": active_blockers,
        "operation_boundaries": {
            "read_only_api_allowed": True,
            "request_send_performed": False,
            "workflow_modification_allowed": False,
            "workflow_trigger_allowed": False,
            "runner_label_change_allowed": False,
            "runner_registration_allowed": False,
            "runner_restart_allowed": False,
            "runner_container_stop_allowed": False,
            "secret_read_allowed": False,
            "secret_plaintext_allowed": False,
            "runner_token_read_allowed": False,
            "gitea_api_write_allowed": False,
            "github_api_used": False,
        },
    }


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 _first_string(value: Any) -> str:
    values = _strings(value)
    return values[0] if values else ""
