"""AWOOOI warning-step runtime enablement gate readback."""

from __future__ import annotations

from typing import Any

from src.services.awoooi_gitea_onboarding_warning_step_template_copy_receipt import (
    load_latest_awoooi_gitea_onboarding_warning_step_template_copy_receipt,
)

_SCHEMA_VERSION = "awoooi_gitea_onboarding_warning_step_runtime_enablement_gate_v1"
_RECEIPT_READY_STATUS = "controlled_template_copy_receipt_ready"
_WORKFLOW_PATH = ".gitea/workflows/awoooi-onboarding-warning-step.yaml"


def load_latest_awoooi_gitea_onboarding_warning_step_runtime_enablement_gate() -> dict[
    str, Any
]:
    """Return the controlled gate for enabling the copied warning-step runtime."""

    receipt = load_latest_awoooi_gitea_onboarding_warning_step_template_copy_receipt()
    receipt_rollups = _dict(receipt.get("rollups"))
    receipt_boundaries = _dict(receipt.get("operation_boundaries"))
    receipt_readback = _dict(receipt.get("readback"))
    switch_value = str(
        receipt_rollups.get("runtime_execution_switch_value")
        or ("1" if receipt_rollups.get("runtime_execution_enabled") is True else "0")
    )
    runtime_enabled = switch_value == "1"
    receipt_ready = (
        receipt.get("status") == _RECEIPT_READY_STATUS
        and receipt.get("active_blockers") == []
        and receipt_rollups.get("workflow_file_present") is True
        and receipt_rollups.get("workflow_matches_template") is True
        and receipt_rollups.get("workflow_dispatch_declared") is True
        and receipt_rollups.get("auto_branch_event_count") == 0
        and receipt_rollups.get("generic_runner_label_count") == 0
        and receipt_rollups.get("runtime_execution_switch_controlled") is True
        and receipt_boundaries.get("workflow_trigger_performed") is False
    )
    active_blockers = _active_blockers(
        receipt_ready=receipt_ready,
        receipt_rollups=receipt_rollups,
        receipt_boundaries=receipt_boundaries,
    )

    return {
        "schema_version": _SCHEMA_VERSION,
        "priority": "P0-004",
        "scope": "gitea_onboarding_warning_step_runtime_enablement",
        "status": (
            "blocked_warning_step_runtime_enablement_gate"
            if active_blockers
            else "controlled_warning_step_runtime_enabled"
            if runtime_enabled
            else "controlled_warning_step_runtime_enablement_gate_ready"
        ),
        "readback": {
            "workplan_id": "P0-004-WARNING-STEP-RUNTIME-ENABLEMENT",
            "source_receipt_status": receipt.get("status"),
            "source_receipt_endpoint": (
                "/api/v1/agents/"
                "awoooi-gitea-onboarding-warning-step-template-copy-receipt"
            ),
            "workflow_path": receipt_readback.get(
                "destination_workflow_path",
                _WORKFLOW_PATH,
            ),
            "workflow_content_source": receipt_readback.get("workflow_content_source"),
            "workflow_content_sha256_12": receipt_readback.get(
                "workflow_content_sha256_12"
            ),
            "runtime_enablement_switch": "AWOOOI_ONBOARDING_WARNING_STEP_EXECUTION_ENABLED",
            "previous_switch_value_before_controlled_apply": "0",
            "current_switch_default": switch_value,
            "desired_switch_value_after_controlled_apply": "1",
            "safe_next_step": (
                "verify_production_runtime_switch_readback_then_open_controlled_dispatch_gate_after_pressure_guard"
                if runtime_enabled
                else "prepare_controlled_switch_flip_with_pressure_guard_then_verify_no_auto_branch_trigger"
            ),
        },
        "controlled_apply": {
            "mode": (
                "controlled_apply_completed"
                if runtime_enabled
                else "controlled_apply_prepared"
            ),
            "controlled_apply_allowed": not active_blockers,
            "controlled_apply_completed": runtime_enabled and not active_blockers,
            "workflow_runtime_enablement_authorized": not active_blockers,
            "workflow_dispatch_authorized": False,
            "auto_push_or_pull_request_trigger_authorized": False,
            "generic_runner_label_authorized": False,
            "runner_pressure_guard_required": True,
            "target_selector_required": True,
            "source_of_truth_diff_required": True,
            "check_mode_required": True,
            "rollback_required": True,
            "post_apply_verifier_required": True,
        },
        "target_selector": {
            "selector_type": "workflow_runtime_enablement_switch",
            "workflow_path": _WORKFLOW_PATH,
            "env_key": "AWOOOI_ONBOARDING_WARNING_STEP_EXECUTION_ENABLED",
            "previous_expected_value_before_controlled_apply": "0",
            "expected_current_value": switch_value,
            "desired_value_after_controlled_apply": "1",
            "allowed_runner_label": "awoooi-non110-host",
        },
        "source_of_truth_diff": {
            "current_state": (
                "warning_step_runtime_job_enabled_for_controlled_dispatch_only"
                if runtime_enabled
                else "warning_step_runtime_job_fail_closed_disabled"
            ),
            "desired_state": "warning_step_runtime_job_enabled_for_controlled_dispatch_only",
            "delta_kind": "env_switch_value_change",
            "auto_branch_event_delta_allowed": False,
            "generic_runner_label_delta_allowed": False,
            "workflow_dispatch_delta_allowed": False,
            "raw_secret_payload_included": False,
        },
        "check_mode": {
            "enabled": True,
            "required": True,
            "checks": [
                "verify_template_copy_receipt_ready",
                "run_runner_pressure_guard",
                "verify_no_push_pull_request_triggers",
                "verify_no_generic_runner_labels",
                (
                    "verify_switch_enabled_for_controlled_dispatch_only"
                    if runtime_enabled
                    else "verify_switch_currently_fail_closed"
                ),
                "verify_git_diff_contains_only_switch_change",
            ],
        },
        "rollback": {
            "required": True,
            "strategy": "restore_warning_step_execution_switch_to_zero",
            "paths": [_WORKFLOW_PATH],
        },
        "post_apply_verifier": {
            "required": True,
            "verifier_refs": [
                "python3 ops/runner/guard-gitea-runner-pressure.py --root .",
                "git diff --check",
                (
                    "pytest apps/api/tests/"
                    "test_p0_cicd_baseline_source_readiness_api.py"
                ),
            ],
            "production_readback": (
                "/api/v1/agents/"
                "awoooi-gitea-onboarding-warning-step-runtime-enablement-gate"
            ),
        },
        "rollups": {
            "template_copy_receipt_ready": receipt_ready,
            "workflow_file_present": receipt_rollups.get("workflow_file_present") is True,
            "workflow_matches_template": (
                receipt_rollups.get("workflow_matches_template") is True
            ),
            "workflow_dispatch_declared": (
                receipt_rollups.get("workflow_dispatch_declared") is True
            ),
            "auto_branch_event_count": _int(receipt_rollups.get("auto_branch_event_count")),
            "generic_runner_label_count": _int(
                receipt_rollups.get("generic_runner_label_count")
            ),
            "fail_closed_execution_switch_present": (
                receipt_rollups.get("fail_closed_execution_switch_present") is True
            ),
            "runtime_execution_switch_controlled": (
                receipt_rollups.get("runtime_execution_switch_controlled") is True
            ),
            "runtime_execution_switch_value": switch_value,
            "runtime_execution_switch_enabled": runtime_enabled,
            "runtime_enablement_switch_present": (
                receipt_rollups.get("runtime_enablement_switch_present") is True
            ),
            "runtime_execution_enabled": runtime_enabled,
            "runner_pressure_guard_required": True,
            "controlled_runtime_enablement_ready": not active_blockers,
            "active_blocker_count": len(active_blockers),
            "workflow_trigger_performed": False,
            "runtime_switch_changed": runtime_enabled,
        },
        "active_blockers": active_blockers,
        "operation_boundaries": {
            "readback_only": True,
            "controlled_runtime_enablement_gate_open": not active_blockers,
            "workflow_file_modified_by_this_endpoint": False,
            "workflow_trigger_performed": False,
            "auto_push_or_pull_request_trigger_allowed": False,
            "generic_runner_label_allowed": False,
            "github_api_used": False,
            "secret_value_collection_allowed": False,
            "host_or_k8s_write_performed": False,
            "raw_session_or_sqlite_read_allowed": False,
        },
    }


def _active_blockers(
    *,
    receipt_ready: bool,
    receipt_rollups: dict[str, Any],
    receipt_boundaries: dict[str, Any],
) -> list[str]:
    blockers: list[str] = []
    if not receipt_ready:
        blockers.append("template_copy_receipt_not_ready")
    if receipt_rollups.get("auto_branch_event_count") != 0:
        blockers.append("auto_branch_event_present_in_workflow")
    if receipt_rollups.get("generic_runner_label_count") != 0:
        blockers.append("generic_runner_label_present_in_workflow")
    if receipt_rollups.get("runtime_execution_switch_controlled") is not True:
        blockers.append("runtime_execution_switch_not_controlled")
    if receipt_boundaries.get("workflow_trigger_performed") is not False:
        blockers.append("workflow_trigger_already_performed")
    return _unique(blockers)


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


def _int(value: Any) -> int:
    try:
        return int(value or 0)
    except (TypeError, ValueError):
        return 0


def _unique(values: list[str]) -> list[str]:
    seen = set()
    result = []
    for value in values:
        if value in seen:
            continue
        seen.add(value)
        result.append(value)
    return result
