// SPEC: PJ2026-01060307 控制面模块化 draft-2026-06-25-p0. remote-python-sync module for scripts/src/platform-infra-sub2api-codex.ts.

// Moved mechanically from scripts/src/platform-infra-sub2api-codex.ts:4265-5400 for #903.

import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import type { UniDeskConfig } from "../config";
import { rootPath } from "../config";
import type { RenderedCliResult } from "../output";
import { applyPk01CaddyBlock, prepareFrpcSecret, renderFrpcManifest, type PublicServiceExposure, type PublicServiceTarget } from "../platform-infra-public-service";
import { shortSha256Fingerprint } from "../platform-infra-ops-library";
import {
  codexPoolSentinelSummary,
  codexPoolSentinelRuntimeImage,
  readCodexPoolSentinelConfig,
  renderCodexPoolSentinelManifest,
  type CodexPoolSentinelConfig,
  type CodexPoolSentinelProfileSecret,
} from "../platform-infra-sub2api-codex-sentinel";
import { parseEnvFile, readTextFile, redactRepoPath, requiredEnvValue } from "../secrets";
import { runSshCommandCapture, type SshCaptureResult } from "../ssh";

import type { CodexPoolConfig, CodexPoolRuntimeTarget } from "./types";
import { desiredAccountCapacityMap, desiredAccountLoadFactorMap, desiredAccountTempUnschedulableMap, desiredAccountWebSocketsV2ModeMap, desiredDefaultAccountTempUnschedulable } from "./accounts";
import { resolvedManualAccountProtections } from "./public-exposure";
import { fieldManager } from "./types";

function pyJson(value: unknown): string {
  return `json.loads(${JSON.stringify(JSON.stringify(value))})`;
}

export function remotePythonCoreScript(mode: "sync" | "validate" | "trace" | "cleanup-probes" | "sentinel-probe" | "profit" | "credits" | "announcements", encodedPayload: string, pool: CodexPoolConfig, target: CodexPoolRuntimeTarget): string {
  const hostDockerEnvPath = target.runtimeMode === "host-docker" ? target.hostDockerEnvPath : null;
  return `
set -u
python3 - <<'PY'
import base64
import hashlib
import json
import os
import re
import secrets
import string
import subprocess
import sys
import time
from datetime import datetime, timezone, timedelta
from urllib.parse import quote

TARGET_ID = ${pyJson(target.id)}
RUNTIME_MODE = ${pyJson(target.runtimeMode)}
NAMESPACE = ${pyJson(target.namespace)}
SERVICE_NAME = ${pyJson(target.serviceName)}
SERVICE_DNS = ${pyJson(target.serviceDns)}
HOST_DOCKER_APP_PORT = ${pyJson(target.hostDockerAppPort)}
HOST_DOCKER_ENV_PATH = ${pyJson(hostDockerEnvPath)}
HOST_DOCKER_APP_CONTAINER = "sub2api-app"
FIELD_MANAGER = "${fieldManager}"
APP_SECRET_NAME = ${pyJson(target.appSecretName)}
POOL_GROUP_NAME = "${pool.groupName}"
POOL_GROUP_DESCRIPTION = ${pyJson(pool.groupDescription)}
POOL_API_KEY_NAME = "${pool.apiKeyName}"
POOL_API_KEY_SECRET_NAME = "${pool.apiKeySecretName}"
POOL_API_KEY_SECRET_KEY = "${pool.apiKeySecretKey}"
POOL_ADMIN_EMAIL_DEFAULT = ${pyJson(pool.adminEmailDefault)}
MIN_OWNER_BALANCE_USD = ${pyJson(pool.minOwnerBalanceUsd)}
MIN_OWNER_CONCURRENCY = ${pyJson(pool.minOwnerConcurrency)}
MIN_OWNER_CONCURRENCY_SOURCE = ${pyJson(pool.minOwnerConcurrencySource)}
POOL_DEFAULT_ACCOUNT_PRIORITY = ${pyJson(pool.defaultAccountPriority)}
POOL_DEFAULT_ACCOUNT_CAPACITY = ${pyJson(pool.defaultAccountCapacity)}
POOL_DEFAULT_ACCOUNT_LOAD_FACTOR = ${pyJson(pool.defaultAccountLoadFactor)}
RESPONSES_SMOKE_MODEL = ${pyJson(pool.localCodex.responsesSmokeModel)}
EXPECTED_ACCOUNT_CAPACITIES = ${pyJson(desiredAccountCapacityMap(pool))}
EXPECTED_ACCOUNT_LOAD_FACTORS = ${pyJson(desiredAccountLoadFactorMap(pool))}
EXPECTED_ACCOUNT_WS_MODES = json.loads(${JSON.stringify(JSON.stringify(desiredAccountWebSocketsV2ModeMap(pool)))})
EXPECTED_ACCOUNT_TEMP_UNSCHEDULABLE = json.loads(${JSON.stringify(JSON.stringify(desiredAccountTempUnschedulableMap(pool)))})
EXPECTED_DEFAULT_TEMP_UNSCHEDULABLE = json.loads(${JSON.stringify(JSON.stringify(desiredDefaultAccountTempUnschedulable(pool)))})
MANUAL_ACCOUNT_PROTECTIONS = json.loads(${JSON.stringify(JSON.stringify(resolvedManualAccountProtections(pool, target)))})
SENTINEL_CONFIG = json.loads(${JSON.stringify(JSON.stringify(pool.sentinel))})
TARGET_EGRESS_PROXY = json.loads(${JSON.stringify(JSON.stringify(target.egressProxy))})
TARGET_SENTINEL_ENABLED = ${target.sentinelEnabled ? "True" : "False"}
MODE = "${mode}"
PAYLOAD_B64 = "${encodedPayload}"

def run(cmd, input_bytes=None):
    return subprocess.run(cmd, input=input_bytes, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

def text(data, limit=4000):
    if isinstance(data, bytes):
        data = data.decode("utf-8", errors="replace")
    return data[-limit:]

def read_host_env():
    if RUNTIME_MODE != "host-docker":
        return {}
    if not isinstance(HOST_DOCKER_ENV_PATH, str) or not HOST_DOCKER_ENV_PATH:
        raise RuntimeError("host-docker env source path missing")
    values = {}
    lines = read_host_env_lines()
    for line in lines:
        stripped = line.strip()
        if not stripped or stripped.startswith("#") or "=" not in stripped:
            continue
        key, value = stripped.split("=", 1)
        key = key.strip()
        value = value.strip()
        if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
            value = value[1:-1]
        if key:
            values[key] = value
    return values

def read_host_env_lines():
    try:
        with open(HOST_DOCKER_ENV_PATH, "r", encoding="utf-8") as handle:
            return handle.read().splitlines()
    except FileNotFoundError:
        raise RuntimeError(f"host-docker env source missing: {HOST_DOCKER_ENV_PATH}")
    except PermissionError:
        proc = run(["sudo", "-n", "cat", HOST_DOCKER_ENV_PATH])
        if proc.returncode != 0:
            raise RuntimeError("read host-docker env source failed: " + text(proc.stderr, 1000))
        return proc.stdout.decode("utf-8", errors="replace").splitlines()

def write_host_env_value(key, value):
    if RUNTIME_MODE != "host-docker":
        raise RuntimeError("write_host_env_value is only valid for host-docker")
    if not isinstance(HOST_DOCKER_ENV_PATH, str) or not HOST_DOCKER_ENV_PATH:
        raise RuntimeError("host-docker env source path missing")
    if not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", key):
        raise RuntimeError(f"unsupported env key: {key}")
    os.makedirs(os.path.dirname(HOST_DOCKER_ENV_PATH), exist_ok=True)
    try:
        lines = read_host_env_lines()
    except RuntimeError as exc:
        if "missing" not in str(exc):
            raise
        lines = []
    next_lines = []
    replaced = False
    for line in lines:
        stripped = line.strip()
        if stripped.startswith("#") or "=" not in stripped:
            next_lines.append(line)
            continue
        current_key = stripped.split("=", 1)[0].strip()
        if current_key == key:
            next_lines.append(f"{key}={value}")
            replaced = True
        else:
            next_lines.append(line)
    if not replaced:
        next_lines.append(f"{key}={value}")
    content = "\\n".join(next_lines).rstrip() + "\\n"
    tmp_path = HOST_DOCKER_ENV_PATH + ".tmp"
    try:
        with open(tmp_path, "w", encoding="utf-8") as handle:
            handle.write(content)
        os.chmod(tmp_path, 0o600)
        os.replace(tmp_path, HOST_DOCKER_ENV_PATH)
    except PermissionError:
        try:
            os.unlink(tmp_path)
        except Exception:
            pass
        script = r'''
set -eu
path="$1"
dir="$(dirname "$path")"
mkdir -p "$dir"
tmp="$path.tmp.$$"
umask 077
cat > "$tmp"
mv "$tmp" "$path"
chmod 600 "$path"
'''
        proc = run(["sudo", "-n", "sh", "-c", script, "sh", HOST_DOCKER_ENV_PATH], content.encode("utf-8"))
        if proc.returncode != 0:
            raise RuntimeError("write host-docker env source failed: " + text(proc.stderr, 1000))
    return "updated" if replaced else "created"

def docker(args):
    proc = run(["docker", *args])
    if proc.returncode == 0:
        return proc
    sudo_proc = run(["sudo", "-n", "docker", *args])
    return sudo_proc if sudo_proc.returncode == 0 else proc

def runtime_logs(since, tail):
    if RUNTIME_MODE == "host-docker":
        return docker(["logs", f"--since={since}", f"--tail={tail}", HOST_DOCKER_APP_CONTAINER])
    return kubectl(["-n", NAMESPACE, "logs", "deployment/sub2api", f"--since={since}", f"--tail={tail}"])

def kubectl(args, input_obj=None):
    if isinstance(input_obj, str):
        input_bytes = input_obj.encode("utf-8")
    else:
        input_bytes = input_obj
    return run(["kubectl", *args], input_bytes)

def require_kubectl(args, input_obj=None, label="kubectl"):
    proc = kubectl(args, input_obj)
    if proc.returncode != 0:
        raise RuntimeError(f"{label} failed: {text(proc.stderr, 1000)}")
    return proc.stdout

def kube_json(args, label):
    raw = require_kubectl([*args, "-o", "json"], label=label)
    return json.loads(raw.decode("utf-8"))

def decode_secret_value(name, key):
    if RUNTIME_MODE == "host-docker":
        return read_host_env().get(key)
    data = kube_json(["-n", NAMESPACE, "get", "secret", name], f"secret/{name}").get("data") or {}
    if key not in data:
        return None
    return base64.b64decode(data[key]).decode("utf-8")

def get_config_value(name, key):
    if RUNTIME_MODE == "host-docker":
        return read_host_env().get(key)
    data = kube_json(["-n", NAMESPACE, "get", "configmap", name], f"configmap/{name}").get("data") or {}
    value = data.get(key)
    return value if isinstance(value, str) and value else None

def select_app_pod():
    if RUNTIME_MODE == "host-docker":
        return HOST_DOCKER_APP_CONTAINER
    pods = kube_json(["-n", NAMESPACE, "get", "pods", "-l", "app.kubernetes.io/name=sub2api"], "sub2api pods").get("items") or []
    for pod in pods:
        status = pod.get("status") or {}
        if status.get("phase") != "Running":
            continue
        statuses = status.get("containerStatuses") or []
        if statuses and all(item.get("ready") is True for item in statuses):
            return pod["metadata"]["name"]
    if pods:
        return pods[0]["metadata"]["name"]
    raise RuntimeError("sub2api app pod not found")

APP_POD = select_app_pod()

def parse_curl_output(proc):
    stdout = proc.stdout.decode("utf-8", errors="replace")
    marker = "\\n__HTTP_CODE__:"
    pos = stdout.rfind(marker)
    if pos < 0:
        return {
            "ok": False,
            "httpStatus": 0,
            "json": None,
            "body": stdout,
            "stderr": text(proc.stderr, 1000),
            "transportExitCode": proc.returncode,
        }
    body = stdout[:pos]
    status_text = stdout[pos + len(marker):].strip()
    try:
        http_status = int(status_text[-3:])
    except ValueError:
        http_status = 0
    try:
        parsed = json.loads(body) if body.strip() else None
    except json.JSONDecodeError:
        parsed = None
    return {
        "ok": proc.returncode == 0 and 200 <= http_status < 300,
        "httpStatus": http_status,
        "json": parsed,
        "body": body,
        "stderr": text(proc.stderr, 1000),
        "transportExitCode": proc.returncode,
    }

def utc_iso(offset_seconds=0):
    return (datetime.now(timezone.utc) + timedelta(seconds=offset_seconds)).strftime("%Y-%m-%dT%H:%M:%SZ")

def normalize_runtime_base_url(value):
    if not isinstance(value, str):
        return None
    value = value.strip().rstrip("/")
    return value or None

def empty_to_none(value):
    return value if isinstance(value, str) and value else None

def sentinel_quality_gate_enabled():
    return TARGET_SENTINEL_ENABLED and (SENTINEL_CONFIG.get("monitor") or {}).get("enabled") is True and (SENTINEL_CONFIG.get("actions") or {}).get("enabled") is True

def account_notes_fingerprint(account):
    notes = account.get("notes") if isinstance(account, dict) else None
    if not isinstance(notes, str):
        return None
    match = re.search(r"fingerprint=([A-Za-z0-9_-]+)", notes)
    return match.group(1) if match else None

def runtime_account_credentials(account):
    credentials = account.get("credentials") if isinstance(account, dict) and isinstance(account.get("credentials"), dict) else {}
    return credentials

def runtime_account_extra(account):
    extra = account.get("extra") if isinstance(account, dict) and isinstance(account.get("extra"), dict) else {}
    return extra

def sentinel_probe_change_reasons(current, profile):
    if not isinstance(current, dict) or current.get("id") is None:
        return ["created"]
    credentials = runtime_account_credentials(current)
    extra = runtime_account_extra(current)
    expected_base_url = normalize_runtime_base_url(profile.get("baseUrl"))
    runtime_base_url = normalize_runtime_base_url(credentials.get("base_url"))
    expected_user_agent = empty_to_none(profile.get("upstreamUserAgent"))
    runtime_user_agent = empty_to_none(credentials.get("user_agent"))
    expected_ws_mode = empty_to_none(profile.get("openaiResponsesWebSocketsV2Mode"))
    runtime_ws_mode = empty_to_none(extra.get("openai_apikey_responses_websockets_v2_mode"))
    expected_trust_upstream = profile.get("trustUpstream") is True
    runtime_trust_upstream = extra.get("unidesk_trust_upstream") is True
    expected_protect = profile.get("sentinelProtect") if isinstance(profile.get("sentinelProtect"), dict) else {"enabled": False}
    runtime_protect = extra.get("unidesk_sentinel_protect") if isinstance(extra.get("unidesk_sentinel_protect"), dict) else {"enabled": False}
    reasons = []
    if empty_to_none(extra.get("unidesk_codex_profile")) != profile.get("profile"):
        reasons.append("profile")
    if runtime_base_url != expected_base_url:
        reasons.append("base-url")
    if account_notes_fingerprint(current) != profile.get("apiKeyFingerprint"):
        reasons.append("api-key-fingerprint")
    if runtime_user_agent != expected_user_agent:
        reasons.append("upstream-user-agent")
    if runtime_ws_mode != expected_ws_mode:
        reasons.append("responses-websockets-v2-mode")
    if runtime_trust_upstream != expected_trust_upstream:
        reasons.append("trust-upstream")
    if runtime_protect != expected_protect:
        reasons.append("sentinel-protect")
    return reasons

def curl_api(method, path, bearer=None, payload=None, idempotency_key=None):
    body = b"" if payload is None else json.dumps(payload, separators=(",", ":")).encode("utf-8")
    script = r'''
set -eu
method="$1"
url="$2"
token="\${3:-}"
idempotency_key="\${4:-}"
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT
cat > "$tmp"
if [ -n "$token" ]; then
  if [ "$method" = "GET" ] && [ ! -s "$tmp" ]; then
    curl -sS -w '\\n__HTTP_CODE__:%{http_code}' -X "$method" -H "Authorization: Bearer $token" "$url"
  else
    if [ -n "$idempotency_key" ]; then
      curl -sS -w '\\n__HTTP_CODE__:%{http_code}' -X "$method" -H 'Content-Type: application/json' -H "Authorization: Bearer $token" -H "Idempotency-Key: $idempotency_key" --data-binary @"$tmp" "$url"
    else
      curl -sS -w '\\n__HTTP_CODE__:%{http_code}' -X "$method" -H 'Content-Type: application/json' -H "Authorization: Bearer $token" --data-binary @"$tmp" "$url"
    fi
  fi
else
  if [ "$method" = "GET" ] && [ ! -s "$tmp" ]; then
    curl -sS -w '\\n__HTTP_CODE__:%{http_code}' -X "$method" "$url"
  else
    curl -sS -w '\\n__HTTP_CODE__:%{http_code}' -X "$method" -H 'Content-Type: application/json' --data-binary @"$tmp" "$url"
  fi
fi
'''
    if RUNTIME_MODE == "host-docker":
        if not isinstance(HOST_DOCKER_APP_PORT, int):
            raise RuntimeError("host-docker app port missing")
        proc = run(["sh", "-c", script, "sh", method, f"http://127.0.0.1:{HOST_DOCKER_APP_PORT}{path}", bearer or "", idempotency_key or ""], body)
    else:
        proc = run([
            "kubectl", "-n", NAMESPACE, "exec", "-i", APP_POD,
            "--", "sh", "-c", script, "sh", method, f"http://127.0.0.1:8080{path}", bearer or "", idempotency_key or "",
        ], body)
    return parse_curl_output(proc)

def envelope_data(parsed):
    if isinstance(parsed, dict) and "data" in parsed:
        return parsed.get("data")
    return parsed

def ensure_success(resp, label):
    parsed = resp.get("json")
    code = parsed.get("code") if isinstance(parsed, dict) else None
    if not resp.get("ok") or (code is not None and code != 0):
        message = parsed.get("message") if isinstance(parsed, dict) else text(resp.get("body", ""), 500)
        raise RuntimeError(f"{label} failed: http={resp.get('httpStatus')} message={message}")
    return envelope_data(parsed)

def ensure_admin_compliance(token):
    status_resp = curl_api("GET", "/api/v1/admin/compliance", bearer=token)
    if status_resp.get("httpStatus") == 404:
        return {
            "ok": True,
            "action": "not-supported-by-runtime",
            "valuesPrinted": False,
        }
    status = ensure_success(status_resp, "get admin compliance")
    if not isinstance(status, dict):
        return {
            "ok": True,
            "action": "status-unstructured",
            "valuesPrinted": False,
        }
    version = status.get("version")
    required = status.get("required") is True
    if not required:
        return {
            "ok": True,
            "action": "already-acknowledged",
            "version": version,
            "requiredBefore": False,
            "requiredAfter": False,
            "phrasePrinted": False,
            "valuesPrinted": False,
        }
    phrase = status.get("ack_phrase_zh") if isinstance(status.get("ack_phrase_zh"), str) and status.get("ack_phrase_zh") else status.get("ack_phrase_en")
    language = "zh" if isinstance(status.get("ack_phrase_zh"), str) and status.get("ack_phrase_zh") else "en"
    if not isinstance(phrase, str) or not phrase:
        raise RuntimeError("admin compliance acknowledgement phrase missing")
    accepted = ensure_success(
        curl_api("POST", "/api/v1/admin/compliance/accept", bearer=token, payload={"phrase": phrase, "language": language}),
        "accept admin compliance",
    )
    required_after = accepted.get("required") if isinstance(accepted, dict) else None
    return {
        "ok": required_after is False,
        "action": "accepted",
        "version": version,
        "requiredBefore": True,
        "requiredAfter": required_after,
        "phrasePrinted": False,
        "valuesPrinted": False,
    }

def extract_items(data):
    if isinstance(data, list):
        return data
    if isinstance(data, dict):
        if isinstance(data.get("items"), list):
            return data["items"]
        for key in ("groups", "accounts", "api_keys", "keys"):
            if isinstance(data.get(key), list):
                return data[key]
    return []

def find_access_token(data):
    if isinstance(data, dict):
        for key in ("access_token", "token"):
            if isinstance(data.get(key), str) and data[key]:
                return data[key]
        for value in data.values():
            token = find_access_token(value)
            if token:
                return token
    return None

def login():
    admin_email = get_config_value("sub2api-config", "ADMIN_EMAIL") or POOL_ADMIN_EMAIL_DEFAULT
    admin_password = decode_secret_value(APP_SECRET_NAME, "ADMIN_PASSWORD")
    if not admin_password:
        raise RuntimeError("ADMIN_PASSWORD missing from sub2api-secrets")
    data = ensure_success(curl_api("POST", "/api/v1/auth/login", payload={"email": admin_email, "password": admin_password}), "admin login")
    token = find_access_token(data)
    if not token:
        raise RuntimeError("admin login response did not contain access_token")
    compliance = ensure_admin_compliance(token)
    if compliance.get("ok") is not True:
        raise RuntimeError("admin compliance acknowledgement failed")
    return admin_email, token, compliance

def group_payload():
    return {
        "name": POOL_GROUP_NAME,
        "description": POOL_GROUP_DESCRIPTION,
        "platform": "openai",
        "rate_multiplier": 1,
        "is_exclusive": False,
        "subscription_type": "standard",
        "allow_messages_dispatch": True,
        "require_oauth_only": False,
        "require_privacy_set": False,
        "rpm_limit": 0,
    }

def list_groups(token):
    data = ensure_success(curl_api("GET", "/api/v1/admin/groups/all?platform=openai", bearer=token), "list groups")
    return extract_items(data)

def ensure_group(token):
    existing = next((item for item in list_groups(token) if item.get("name") == POOL_GROUP_NAME), None)
    payload = group_payload()
    if existing is None:
        created = ensure_success(curl_api("POST", "/api/v1/admin/groups", bearer=token, payload=payload), "create group")
        return created, "created"
    group_id = existing.get("id")
    if group_id is None:
        raise RuntimeError("existing group has no id")
    payload["status"] = "active"
    updated = ensure_success(curl_api("PUT", f"/api/v1/admin/groups/{group_id}", bearer=token, payload=payload), "update group")
    return updated if isinstance(updated, dict) else existing, "updated"

def list_accounts_for_group(token, group_id):
    path = f"/api/v1/admin/accounts?group_id={group_id}&page=1&page_size=500&platform=openai"
    data = ensure_success(curl_api("GET", path, bearer=token), f"list accounts for group {group_id}")
    return extract_items(data)

def account_group_ids(token, account):
    if not isinstance(account, dict) or account.get("id") is None:
        return []
    account_id = account.get("id")
    account_name = account.get("name")
    ids = []
    for group in list_groups(token):
        group_id = group.get("id") if isinstance(group, dict) else None
        if group_id is None:
            continue
        members = list_accounts_for_group(token, group_id)
        if any(item.get("id") == account_id or item.get("name") == account_name for item in members if isinstance(item, dict)):
            ids.append(group_id)
    return sorted(set(ids))

def list_accounts(token):
    path = "/api/v1/admin/accounts?page=1&page_size=200&platform=openai&type=apikey&search=" + quote("unidesk-codex-")
    data = ensure_success(curl_api("GET", path, bearer=token), "list accounts")
    return extract_items(data)

def find_account_by_name(token, name):
    path = "/api/v1/admin/accounts?page=1&page_size=50&platform=openai&search=" + quote(str(name))
    data = ensure_success(curl_api("GET", path, bearer=token), "find account " + str(name))
    for item in extract_items(data):
        if isinstance(item, dict) and item.get("name") == name:
            return item
    return None

def list_proxy_candidates(token, search=""):
    path = "/api/v1/admin/proxies?page=1&page_size=200"
    if search:
        path += "&search=" + quote(str(search))
    data = ensure_success(curl_api("GET", path, bearer=token), "list proxies")
    return extract_items(data)

def find_proxy_by_name(token, name):
    for item in list_proxy_candidates(token, name):
        if isinstance(item, dict) and item.get("name") == name:
            return item
    return None

def manual_binding_plan(binding, expected_kind):
    if not isinstance(binding, dict):
        return None
    plan = binding.get("sourcePlan")
    if not isinstance(plan, dict):
        raise RuntimeError("manual account binding is missing resolved sourcePlan")
    if plan.get("enabled") is not True:
        raise RuntimeError(f"manual account binding source {plan.get('id')} is disabled")
    if plan.get("kind") != expected_kind:
        raise RuntimeError(f"manual account binding source {plan.get('id')} kind must be {expected_kind}")
    return plan

def desired_manual_proxy_payload(protection):
    binding = protection.get("proxyBinding") if isinstance(protection, dict) else None
    if not isinstance(binding, dict) or binding.get("enabled") is not True:
        return None
    plan = manual_binding_plan(binding, "proxy")
    if plan.get("provider") not in ("target-egress-proxy", "fixed-http-proxy"):
        raise RuntimeError(f"manual account proxyBinding source {plan.get('id')} uses unsupported provider {plan.get('provider')}")
    if plan.get("provider") == "fixed-http-proxy":
        fixed_proxy = plan.get("fixedProxy")
        if not isinstance(fixed_proxy, dict):
            raise RuntimeError(f"manual account proxyBinding source {plan.get('id')} requires fixedProxy")
        proxy_name = binding.get("proxyName")
        protocol = fixed_proxy.get("protocol")
        host = fixed_proxy.get("host")
        port = fixed_proxy.get("port")
        if not isinstance(proxy_name, str) or not proxy_name:
            raise RuntimeError("manual account proxyBinding proxyName is missing")
        if protocol != "http":
            raise RuntimeError("fixed proxy protocol must be http")
        if not isinstance(host, str) or not host:
            raise RuntimeError("fixed proxy host is missing")
        if not isinstance(port, int) or port <= 0:
            raise RuntimeError("fixed proxy port is missing")
        return {
            "name": proxy_name,
            "protocol": protocol,
            "host": host,
            "port": port,
            "fallback_mode": "none",
            "expiry_warn_days": 0,
        }
    target_proxy = plan.get("targetEgressProxy")
    if not isinstance(target_proxy, dict):
        raise RuntimeError(f"manual account proxyBinding source {plan.get('id')} requires an enabled target egressProxy")
    service_name = target_proxy.get("serviceName")
    listen_port = target_proxy.get("listenPort")
    namespace = target_proxy.get("namespace") if isinstance(target_proxy.get("namespace"), str) and target_proxy.get("namespace") else NAMESPACE
    proxy_name = binding.get("proxyName")
    if not isinstance(service_name, str) or not service_name:
        raise RuntimeError("target egressProxy serviceName is missing")
    if not isinstance(listen_port, int) or listen_port <= 0:
        raise RuntimeError("target egressProxy listenPort is missing")
    if not isinstance(proxy_name, str) or not proxy_name:
        raise RuntimeError("manual account proxyBinding proxyName is missing")
    return {
        "name": proxy_name,
        "protocol": "http",
        "host": f"{service_name}.{namespace}.svc.cluster.local",
        "port": listen_port,
        "fallback_mode": "none",
        "expiry_warn_days": 0,
    }

def proxy_needs_update(proxy, payload):
    if not isinstance(proxy, dict):
        return True
    for key in ("name", "protocol", "host", "port", "fallback_mode", "expiry_warn_days"):
        if proxy.get(key) != payload.get(key):
            return True
    return proxy.get("status") != "active"

def ensure_manual_proxy(token, payload):
    current = find_proxy_by_name(token, payload["name"])
    if current is None:
        created = ensure_success(curl_api("POST", "/api/v1/admin/proxies", bearer=token, payload=payload), f"create proxy {payload['name']}")
        return created, "created"
    if proxy_needs_update(current, payload):
        update_payload = dict(payload)
        update_payload["status"] = "active"
        updated = ensure_success(curl_api("PUT", f"/api/v1/admin/proxies/{current['id']}", bearer=token, payload=update_payload), f"update proxy {payload['name']}")
        return updated if isinstance(updated, dict) else current, "updated"
    return current, "unchanged"

def manual_proxy_status(token, account, protection):
    payload = desired_manual_proxy_payload(protection)
    if payload is None:
        return {
            "enabled": False,
            "ok": True,
            "action": "not-configured",
            "valuesPrinted": False,
        }
    binding = protection.get("proxyBinding") if isinstance(protection, dict) else None
    plan = manual_binding_plan(binding, "proxy")
    proxy = find_proxy_by_name(token, payload["name"])
    runtime_proxy = account.get("proxy") if isinstance(account, dict) and isinstance(account.get("proxy"), dict) else None
    binding_aligned = (
        isinstance(account, dict)
        and isinstance(proxy, dict)
        and account.get("proxy_id") == proxy.get("id")
    )
    return {
        "enabled": True,
        "ok": binding_aligned,
        "action": "validate",
        "source": plan.get("id"),
        "sourceProvider": plan.get("provider"),
        "expectedProxyName": payload["name"],
        "expectedProtocol": payload["protocol"],
        "expectedHost": payload["host"],
        "expectedPort": payload["port"],
        "proxyRecordExists": isinstance(proxy, dict),
        "proxyId": proxy.get("id") if isinstance(proxy, dict) else None,
        "runtimeProxyId": account.get("proxy_id") if isinstance(account, dict) else None,
        "runtimeProxyName": runtime_proxy.get("name") if isinstance(runtime_proxy, dict) else None,
        "bindingAligned": binding_aligned,
        "valuesPrinted": False,
    }

def ensure_manual_account_proxy_bindings(token):
    items = []
    for protection in MANUAL_ACCOUNT_PROTECTIONS:
        if not isinstance(protection, dict):
            continue
        name = protection.get("accountName")
        if not isinstance(name, str) or not name:
            continue
        account = find_account_by_name(token, name)
        payload = desired_manual_proxy_payload(protection)
        if payload is None:
            items.append({
                "accountName": name,
                "enabled": False,
                "action": "not-configured",
                "ok": True,
                "valuesPrinted": False,
            })
            continue
        if not isinstance(account, dict):
            items.append({
                "accountName": name,
                "enabled": True,
                "action": "account-missing",
                "ok": False,
                "expectedProxyName": payload["name"],
                "valuesPrinted": False,
            })
            continue
        proxy, proxy_action = ensure_manual_proxy(token, payload)
        binding = protection.get("proxyBinding") if isinstance(protection, dict) else None
        plan = manual_binding_plan(binding, "proxy")
        proxy_id = proxy.get("id") if isinstance(proxy, dict) else None
        if proxy_id is None:
            raise RuntimeError(f"proxy {payload['name']} has no id")
        action = "unchanged"
        if account.get("proxy_id") != proxy_id:
            updated = ensure_success(curl_api("PUT", f"/api/v1/admin/accounts/{account['id']}", bearer=token, payload={"proxy_id": proxy_id}), f"bind manual account proxy {name}")
            account = updated if isinstance(updated, dict) else account
            action = "bound"
        runtime_proxy = account.get("proxy") if isinstance(account.get("proxy"), dict) else None
        items.append({
            "accountName": name,
            "accountId": account.get("id"),
            "enabled": True,
            "action": action,
            "proxyAction": proxy_action,
            "source": plan.get("id"),
            "sourceProvider": plan.get("provider"),
            "ok": account.get("proxy_id") == proxy_id,
            "expectedProxyName": payload["name"],
            "expectedProtocol": payload["protocol"],
            "expectedHost": payload["host"],
            "expectedPort": payload["port"],
            "proxyId": proxy_id,
            "runtimeProxyId": account.get("proxy_id"),
            "runtimeProxyName": runtime_proxy.get("name") if isinstance(runtime_proxy, dict) else None,
            "bindingAligned": account.get("proxy_id") == proxy_id,
            "controlPolicy": "manual-protected: only proxy_id binding is YAML-controlled; credentials/status/schedulable are untouched",
            "valuesPrinted": False,
        })
    return {
        "ok": all(item.get("ok") is True for item in items),
        "itemCount": len(items),
        "items": items,
        "valuesPrinted": False,
    }

def manual_group_binding_plan(protection):
    binding = protection.get("groupBinding") if isinstance(protection, dict) else None
    if not isinstance(binding, dict) or binding.get("enabled") is not True:
        return None
    plan = manual_binding_plan(binding, "group")
    if plan.get("provider") != "pool-group":
        raise RuntimeError(f"manual account groupBinding source {plan.get('id')} uses unsupported provider {plan.get('provider')}")
    return plan

def manual_group_binding_enabled(protection):
    return manual_group_binding_plan(protection) is not None

def manual_group_status(token, account, protection, group_id):
    plan = manual_group_binding_plan(protection)
    if plan is None:
        return {
            "enabled": False,
            "ok": True,
            "action": "not-configured",
            "valuesPrinted": False,
        }
    group_accounts = list_accounts_for_group(token, group_id)
    account_id = account.get("id") if isinstance(account, dict) else None
    account_name = account.get("name") if isinstance(account, dict) else None
    binding_aligned = any(
        item.get("id") == account_id or item.get("name") == account_name
        for item in group_accounts
        if isinstance(item, dict)
    )
    return {
        "enabled": True,
        "ok": binding_aligned,
        "action": "validate",
        "source": plan.get("id"),
        "sourceProvider": plan.get("provider"),
        "poolGroupName": POOL_GROUP_NAME,
        "poolGroupId": group_id,
        "bindingAligned": binding_aligned,
        "valuesPrinted": False,
    }

def ensure_manual_account_group_bindings(token, group_id):
    items = []
    for protection in MANUAL_ACCOUNT_PROTECTIONS:
        if not isinstance(protection, dict):
            continue
        name = protection.get("accountName")
        if not isinstance(name, str) or not name:
            continue
        if not manual_group_binding_enabled(protection):
            items.append({
                "accountName": name,
                "enabled": False,
                "action": "not-configured",
                "ok": True,
                "valuesPrinted": False,
            })
            continue
        plan = manual_group_binding_plan(protection)
        account = find_account_by_name(token, name)
        if not isinstance(account, dict):
            items.append({
                "accountName": name,
                "enabled": True,
                "action": "account-missing",
                "ok": False,
                "poolGroupName": POOL_GROUP_NAME,
                "poolGroupId": group_id,
                "valuesPrinted": False,
            })
            continue
        existing_group_ids = account_group_ids(token, account)
        desired_group_ids = sorted(set(existing_group_ids + [group_id]))
        action = "unchanged"
        if group_id not in existing_group_ids:
            updated = ensure_success(curl_api("PUT", f"/api/v1/admin/accounts/{account['id']}", bearer=token, payload={"group_ids": desired_group_ids}), f"bind manual account group {name}")
            account = updated if isinstance(updated, dict) else account
            action = "bound"
        binding_aligned = any(
            item.get("id") == account.get("id") or item.get("name") == name
            for item in list_accounts_for_group(token, group_id)
            if isinstance(item, dict)
        )
        items.append({
            "accountName": name,
            "accountId": account.get("id"),
            "enabled": True,
            "ok": binding_aligned,
            "action": action,
            "source": plan.get("id") if isinstance(plan, dict) else None,
            "sourceProvider": plan.get("provider") if isinstance(plan, dict) else None,
            "poolGroupName": POOL_GROUP_NAME,
            "poolGroupId": group_id,
            "previousGroupIds": existing_group_ids,
            "desiredGroupIds": desired_group_ids,
            "bindingAligned": binding_aligned,
            "controlPolicy": "manual-protected: only pool group membership is YAML-controlled; credentials/status/schedulable are untouched and sentinel does not probe it",
            "valuesPrinted": False,
        })
    return {
        "ok": all(item.get("ok") is True for item in items),
        "itemCount": len(items),
        "items": items,
        "valuesPrinted": False,
    }

def manual_account_protection_status(token, group_id=None):
    items = []
    desired_names = set(EXPECTED_ACCOUNT_CAPACITIES.keys())
    for protection in MANUAL_ACCOUNT_PROTECTIONS:
        if not isinstance(protection, dict):
            continue
        name = protection.get("accountName")
        if not isinstance(name, str) or not name:
            continue
        account = find_account_by_name(token, name)
        extra = account.get("extra") if isinstance(account, dict) and isinstance(account.get("extra"), dict) else {}
        proxy_status = manual_proxy_status(token, account, protection)
        group_status = manual_group_status(token, account, protection, group_id) if group_id is not None else {"enabled": False, "ok": True, "action": "not-checked", "valuesPrinted": False}
        items.append({
            "accountName": name,
            "reason": protection.get("reason") if isinstance(protection.get("reason"), str) else None,
            "exists": isinstance(account, dict),
            "accountId": account.get("id") if isinstance(account, dict) else None,
            "status": account.get("status") if isinstance(account, dict) else None,
            "schedulable": account.get("schedulable") if isinstance(account, dict) else None,
            "inYamlProfiles": name in desired_names,
            "runtimeMarkedUnideskManaged": extra.get("unidesk_managed") is True,
            "proxyBinding": proxy_status,
            "groupBinding": group_status,
            "ok": proxy_status.get("ok") is True and group_status.get("ok") is True,
            "controlPolicy": "manual-protected: no create/update/prune/probe/freeze; optional proxy_id and pool group membership binding only when configured",
            "valuesPrinted": False,
        })
    return {
        "ok": all(item.get("ok") is True for item in items),
        "protectedCount": len(items),
        "items": items,
        "valuesPrinted": False,
    }

def list_probe_accounts(token):
    path = "/api/v1/admin/accounts?page=1&page_size=200&platform=openai&type=apikey&search=" + quote("unidesk-probe-")
    data = ensure_success(curl_api("GET", path, bearer=token), "list probe accounts")
    return [item for item in extract_items(data) if isinstance(item.get("name"), str) and item.get("name").startswith("unidesk-probe-")]

def list_probe_groups(token):
    data = ensure_success(curl_api("GET", "/api/v1/admin/groups/all?platform=openai", bearer=token), "list groups")
    return [item for item in extract_items(data) if isinstance(item.get("name"), str) and item.get("name").startswith("unidesk-probe-")]

def cleanup_probe_resources(token):
    api_key_results = []
    account_results = []
    group_results = []
    for item in list_user_keys(token):
        name = item.get("name")
        key_id = item.get("id")
        if not isinstance(name, str) or not name.startswith("unidesk-probe-") or key_id is None:
            continue
        api_key_results.append(delete_probe_resource(token, "DELETE", f"/api/v1/keys/{key_id}", "api-key"))
    for item in list_probe_accounts(token):
        account_id = item.get("id")
        if account_id is None:
            continue
        account_results.append(delete_probe_resource(token, "DELETE", f"/api/v1/admin/accounts/{account_id}", "account"))
    for item in list_probe_groups(token):
        group_id = item.get("id")
        if group_id is None:
            continue
        group_results.append(delete_probe_resource(token, "DELETE", f"/api/v1/admin/groups/{group_id}", "group"))
    return {
        "ok": all(item.get("ok") is True for item in api_key_results + account_results + group_results),
        "apiKeysDeleted": len(api_key_results),
        "accountsDeleted": len(account_results),
        "groupsDeleted": len(group_results),
        "items": {
            "apiKeys": api_key_results,
            "accounts": account_results,
            "groups": group_results,
        },
        "valuesPrinted": False,
    }

def temp_unschedulable_credentials(profile):
    credentials = profile.get("tempUnschedulableCredentials")
    if not isinstance(credentials, dict):
        credentials = {}
    return normalize_temp_unschedulable_credentials(credentials)

def account_payload(profile, group_id):
    extra = {
        "openai_responses_mode": "force_responses",
        "unidesk_codex_profile": profile["profile"],
        "unidesk_managed": True,
        "unidesk_trust_upstream": profile.get("trustUpstream") is True,
        "unidesk_sentinel_protect": profile.get("sentinelProtect") if isinstance(profile.get("sentinelProtect"), dict) else {"enabled": False},
    }
    ws_mode = profile.get("openaiResponsesWebSocketsV2Mode")
    if ws_mode:
        extra["openai_apikey_responses_websockets_v2_mode"] = ws_mode
        extra["openai_apikey_responses_websockets_v2_enabled"] = ws_mode != "off"
    credentials = {
        "api_key": profile["apiKey"],
        "base_url": profile["baseUrl"],
    }
    upstream_user_agent = profile.get("upstreamUserAgent")
    if upstream_user_agent:
        credentials["user_agent"] = upstream_user_agent
    temp_unschedulable = temp_unschedulable_credentials(profile)
    if temp_unschedulable["enabled"]:
        credentials["temp_unschedulable_enabled"] = True
        credentials["temp_unschedulable_rules"] = temp_unschedulable["rules"]
    return {
        "name": profile["accountName"],
        "notes": f"UniDesk-managed Codex profile {profile['profile']} from {profile['configFile']} and {profile['authFile']}; secret source={profile['apiKeySource']}; fingerprint={profile['apiKeyFingerprint']}.",
        "platform": "openai",
        "type": "apikey",
        "credentials": credentials,
        "extra": extra,
        "concurrency": int(profile.get("capacity", 5) or 5),
        "priority": int(profile.get("priority", POOL_DEFAULT_ACCOUNT_PRIORITY) or POOL_DEFAULT_ACCOUNT_PRIORITY),
        "rate_multiplier": 1,
        "load_factor": int(profile.get("loadFactor", POOL_DEFAULT_ACCOUNT_LOAD_FACTOR) or POOL_DEFAULT_ACCOUNT_LOAD_FACTOR),
        "group_ids": [group_id],
        "confirm_mixed_channel_risk": True,
        **({"proxy_id": int(profile["proxyId"])} if profile.get("proxyId") is not None else {}),
    }

def planned_sentinel_account_results(profiles, existing_accounts):
    existing = {item.get("name"): item for item in existing_accounts if isinstance(item, dict)}
    results = []
    for profile in profiles:
        change_reasons = sentinel_probe_change_reasons(existing.get(profile["accountName"]), profile)
        quality_gate_required = sentinel_quality_gate_enabled() and len(change_reasons) > 0
        results.append({
            "profile": profile["profile"],
            "accountName": profile["accountName"],
            "profileConfig": {
                "accountName": profile["accountName"],
                "trustUpstream": profile.get("trustUpstream") is True,
                "sentinelProtect": profile.get("sentinelProtect") if isinstance(profile.get("sentinelProtect"), dict) else {"enabled": False},
            },
            "sentinelProbeConfigFingerprint": profile.get("sentinelProbeConfigFingerprint"),
            "sentinelProbeRequired": quality_gate_required,
            "sentinelChangeReasons": change_reasons if quality_gate_required else [],
            "sentinelProbePending": quality_gate_required,
            "sentinelDefaultFrozen": False,
            "valuesPrinted": False,
        })
    return results

def ensure_accounts(token, profiles, group_id, prune_removed=False, protected_frozen_names=None, existing_accounts=None):
    if not isinstance(protected_frozen_names, set):
        protected_frozen_names = set()
    if not isinstance(existing_accounts, list):
        existing_accounts = list_accounts(token)
    existing = {item.get("name"): item for item in existing_accounts}
    desired_names = {profile["accountName"] for profile in profiles}
    results = []
    for profile in profiles:
        payload = account_payload(profile, group_id)
        current = existing.get(profile["accountName"])
        change_reasons = sentinel_probe_change_reasons(current, profile)
        quality_gate_required = sentinel_quality_gate_enabled() and len(change_reasons) > 0
        keep_frozen = profile["accountName"] in protected_frozen_names
        if current and current.get("id") is not None:
            account_id = current["id"]
            update_payload = dict(payload)
            update_payload.pop("platform", None)
            update_payload["status"] = "active"
            data = ensure_success(curl_api("PUT", f"/api/v1/admin/accounts/{account_id}", bearer=token, payload=update_payload), f"update account {profile['accountName']}")
            action = "updated"
        else:
            data = ensure_success(curl_api("POST", "/api/v1/admin/accounts", bearer=token, payload=payload), f"create account {profile['accountName']}")
            action = "created"
        results.append({
            "profile": profile["profile"],
            "accountName": profile["accountName"],
            "profileConfig": {
                "accountName": profile["accountName"],
                "trustUpstream": profile.get("trustUpstream") is True,
                "sentinelProtect": profile.get("sentinelProtect") if isinstance(profile.get("sentinelProtect"), dict) else {"enabled": False},
            },
            "accountId": data.get("id") if isinstance(data, dict) else None,
            "action": action,
            "baseUrl": profile["baseUrl"],
            "apiKeySource": profile["apiKeySource"],
            "apiKeyFingerprint": profile["apiKeyFingerprint"],
            "sentinelProbeConfigFingerprint": profile.get("sentinelProbeConfigFingerprint"),
            "sentinelProbeRequired": quality_gate_required,
            "sentinelChangeReasons": change_reasons if quality_gate_required else [],
            "sentinelProbePending": quality_gate_required,
            "sentinelDefaultFrozen": False,
            "sentinelFreezeProtected": keep_frozen,
            "schedulableControl": "sentinel-marker-restore",
            "openaiResponsesWebSocketsV2Mode": profile.get("openaiResponsesWebSocketsV2Mode"),
            "trustUpstream": profile.get("trustUpstream") is True,
            "priority": int(profile.get("priority", POOL_DEFAULT_ACCOUNT_PRIORITY) or POOL_DEFAULT_ACCOUNT_PRIORITY),
            "capacity": int(profile.get("capacity", 5) or 5),
            "loadFactor": int(profile.get("loadFactor", POOL_DEFAULT_ACCOUNT_LOAD_FACTOR) or POOL_DEFAULT_ACCOUNT_LOAD_FACTOR),
            "runtimeConcurrency": data.get("concurrency") if isinstance(data, dict) else None,
            "runtimeLoadFactor": data.get("load_factor") if isinstance(data, dict) else None,
            "runtimeSchedulable": data.get("schedulable") if isinstance(data, dict) else None,
            "tempUnschedulableConfigured": bool(payload["credentials"].get("temp_unschedulable_enabled")),
            "tempUnschedulableRuleCount": len(payload["credentials"].get("temp_unschedulable_rules") or []),
            "upstreamUserAgentConfigured": bool(profile.get("upstreamUserAgent")),
            "valuesPrinted": False,
        })
    prune_results = prune_removed_accounts(token, existing_accounts, desired_names) if prune_removed else []
    return results, prune_results

def prune_removed_accounts(token, existing_accounts, desired_names):
    results = []
    for account in existing_accounts:
        name = account.get("name")
        account_id = account.get("id")
        extra = account.get("extra") if isinstance(account.get("extra"), dict) else {}
        if not isinstance(name, str) or not name.startswith("unidesk-codex-"):
            continue
        if extra.get("unidesk_managed") is not True:
            continue
        if name in desired_names:
            continue
        if account_id is None:
            raise RuntimeError(f"removed account {name} has no id")
        ensure_success(curl_api("DELETE", f"/api/v1/admin/accounts/{account_id}", bearer=token), f"delete removed account {name}")
        results.append({
            "accountName": name,
            "accountId": account_id,
            "profile": extra.get("unidesk_codex_profile"),
            "action": "deleted",
            "reason": "removed-from-yaml",
            "valuesPrinted": False,
        })
    return results

def generate_api_key():
    alphabet = string.ascii_letters + string.digits
    return "sk-unidesk-codex-" + "".join(secrets.choice(alphabet) for _ in range(48))

def sub2api_key_value(item):
    if not isinstance(item, dict):
        return None
    key = item.get("key")
    return key if isinstance(key, str) and key else None

def find_pool_key_by_name(keys):
    return next((item for item in keys if isinstance(item, dict) and item.get("name") == POOL_API_KEY_NAME), None)

def existing_sub2api_pool_api_key(token):
    try:
        existing = find_pool_key_by_name(list_user_keys(token))
    except Exception:
        return None
    return sub2api_key_value(existing)

def ensure_pool_api_key_for_validate(token, secret_value, source_action):
    group, group_action = ensure_group(token)
    group_id = group.get("id") if isinstance(group, dict) else None
    if group_id is None:
        raise RuntimeError("pool group id missing while ensuring validate API key")
    api_key = secret_value or generate_api_key()
    api_key_result = ensure_sub2api_api_key(token, api_key, group_id)
    host_env_action = write_host_env_value(POOL_API_KEY_SECRET_KEY, api_key)
    key_item = {
        "id": api_key_result.get("id"),
        "name": api_key_result.get("name") or POOL_API_KEY_NAME,
        "group_id": api_key_result.get("groupId"),
        "user_id": api_key_result.get("userId"),
        "key": api_key,
    }
    return api_key, key_item, {
        "ok": True,
        "source": "sub2api-admin-api",
        "sourceAction": source_action,
        "secretPresent": bool(secret_value),
        "lookup": "ensured-by-admin-api",
        "groupAction": group_action,
        "sub2apiAction": api_key_result.get("action"),
        "sub2apiId": api_key_result.get("id"),
        "hostEnvAction": host_env_action,
        "hostEnvPath": HOST_DOCKER_ENV_PATH,
        "hostEnvKey": POOL_API_KEY_SECRET_KEY,
        "valuesPrinted": False,
    }

def resolve_pool_api_key_for_validate(token):
    secret_value = None
    secret_error = None
    try:
        secret_value = decode_secret_value(POOL_API_KEY_SECRET_NAME, POOL_API_KEY_SECRET_KEY)
    except Exception as exc:
        if RUNTIME_MODE != "host-docker":
            raise
        secret_error = str(exc)
    keys = list_user_keys(token)
    matched_item = None
    if secret_value:
        matched_item = next((item for item in keys if isinstance(item, dict) and item.get("key") == secret_value), None)
        if isinstance(matched_item, dict) and matched_item.get("name") == POOL_API_KEY_NAME:
            return secret_value, matched_item, {
                "ok": True,
                "source": pool_api_key_secret_location(),
                "sourceAction": "kept-existing",
                "secretPresent": True,
                "lookup": "matched-by-value",
                "hostEnvAction": "none",
                "valuesPrinted": False,
            }
    if RUNTIME_MODE == "host-docker":
        named_item = find_pool_key_by_name(keys)
        named_key = sub2api_key_value(named_item)
        if named_key:
            host_env_action = write_host_env_value(POOL_API_KEY_SECRET_KEY, named_key)
            return named_key, named_item, {
                "ok": True,
                "source": "sub2api-admin-api",
                "sourceAction": "recovered-missing" if not secret_value else "repaired-mismatch",
                "secretPresent": bool(secret_value),
                "lookup": "matched-by-name",
                "hostEnvAction": host_env_action,
                "hostEnvPath": HOST_DOCKER_ENV_PATH,
                "hostEnvKey": POOL_API_KEY_SECRET_KEY,
                "valuesPrinted": False,
            }
        if not secret_value:
            return ensure_pool_api_key_for_validate(token, secret_value, "created-missing")
        matched_name = matched_item.get("name") if isinstance(matched_item, dict) else None
        return ensure_pool_api_key_for_validate(token, secret_value, "repaired-mismatch:" + (matched_name or "-"))
    if not secret_value:
        raise RuntimeError(f"{POOL_API_KEY_SECRET_NAME}.{POOL_API_KEY_SECRET_KEY} missing")
    return secret_value, matched_item, {
        "ok": isinstance(matched_item, dict) and matched_item.get("name") == POOL_API_KEY_NAME,
        "source": pool_api_key_secret_location(),
        "sourceAction": "kept-existing",
        "secretPresent": True,
        "lookup": "matched-by-value" if matched_item else "missing-in-admin-api",
        "hostEnvAction": "not-applicable",
        "valuesPrinted": False,
    }

def ensure_api_key_secret(group_id, token):
    existing = None
    try:
        existing = decode_secret_value(POOL_API_KEY_SECRET_NAME, POOL_API_KEY_SECRET_KEY)
    except Exception:
        existing = None
    reused = None if existing else existing_sub2api_pool_api_key(token)
    api_key = existing or reused or generate_api_key()
    if existing:
        secret_action = "kept-existing"
    elif reused:
        secret_action = "reused-existing-sub2api-key"
    else:
        secret_action = "created"
    if RUNTIME_MODE == "host-docker":
        env_action = "kept-existing" if existing else write_host_env_value(POOL_API_KEY_SECRET_KEY, api_key)
        return api_key, secret_action, f"host-docker-env:{env_action};source={HOST_DOCKER_ENV_PATH};key={POOL_API_KEY_SECRET_KEY};valuesPrinted=false"
    manifest = {
        "apiVersion": "v1",
        "kind": "Secret",
        "metadata": {
            "name": POOL_API_KEY_SECRET_NAME,
            "namespace": NAMESPACE,
            "labels": {
                "app.kubernetes.io/name": "sub2api",
                "app.kubernetes.io/part-of": "platform-infra",
                "app.kubernetes.io/managed-by": "unidesk",
                "unidesk.ai/secret-purpose": "sub2api-codex-pool-api-key",
            },
        },
        "type": "Opaque",
        "stringData": {
            POOL_API_KEY_SECRET_KEY: api_key,
            "GROUP_ID": str(group_id),
            "GROUP_NAME": POOL_GROUP_NAME,
            "SERVICE_DNS": SERVICE_DNS,
        },
    }
    proc = kubectl(["apply", "--server-side", "--force-conflicts", f"--field-manager={FIELD_MANAGER}", "-f", "-"], json.dumps(manifest))
    if proc.returncode != 0:
        raise RuntimeError(f"apply API key secret failed: {text(proc.stderr, 1000)}")
    return api_key, secret_action, text(proc.stdout, 1000)

`;
}
