export const remotePythonSentinelScript = `def pool_api_key_secret_location():
    if RUNTIME_MODE == "host-docker":
        return f"{HOST_DOCKER_ENV_PATH}.{POOL_API_KEY_SECRET_KEY}"
    return f"{NAMESPACE}/{POOL_API_KEY_SECRET_NAME}.{POOL_API_KEY_SECRET_KEY}"

def apply_sentinel_manifest(manifest):
    if not TARGET_SENTINEL_ENABLED:
        return {
            "ok": True,
            "action": "skipped-target-disabled",
            "valuesPrinted": False,
        }
    if not isinstance(manifest, str) or not manifest.strip():
        return {
            "ok": False,
            "action": "missing-manifest",
            "valuesPrinted": False,
        }
    proc = kubectl(["apply", "--server-side", "--force-conflicts", f"--field-manager={FIELD_MANAGER}", "-f", "-"], manifest)
    if proc.returncode != 0:
        return {
            "ok": False,
            "action": "apply-failed",
            "stdoutTail": text(proc.stdout, 2000),
            "stderrTail": text(proc.stderr, 4000),
            "valuesPrinted": False,
        }
    status = sentinel_runtime_status()
    return {
        "ok": status.get("ok") is True,
        "action": "applied",
        "stdoutTail": text(proc.stdout, 2000),
        "runtime": status,
        "valuesPrinted": False,
    }

def safe_kube_json(args, label):
    proc = kubectl([*args, "-o", "json"])
    if proc.returncode != 0:
        return None, {"label": label, "exitCode": proc.returncode, "stderrTail": text(proc.stderr, 1000)}
    try:
        return json.loads(proc.stdout.decode("utf-8")), None
    except Exception as exc:
        return None, {"label": label, "exitCode": proc.returncode, "error": str(exc), "stdoutTail": text(proc.stdout, 1000)}

def sentinel_runtime_status():
    if not TARGET_SENTINEL_ENABLED:
        return {
            "ok": True,
            "action": "skipped-target-disabled",
            "desired": {
                "monitorEnabled": SENTINEL_CONFIG.get("monitor", {}).get("enabled"),
                "actionsEnabled": SENTINEL_CONFIG.get("actions", {}).get("enabled"),
            },
            "valuesPrinted": False,
        }
    cfg = SENTINEL_CONFIG
    cronjob_name = cfg.get("cronJobName")
    secret_name = cfg.get("credentialsSecretName")
    configmap_name = cfg.get("configMapName")
    state_name = cfg.get("stateConfigMapName")
    cronjob, cronjob_error = safe_kube_json(["-n", NAMESPACE, "get", "cronjob", cronjob_name], f"cronjob/{cronjob_name}")
    secret, secret_error = safe_kube_json(["-n", NAMESPACE, "get", "secret", secret_name], f"secret/{secret_name}")
    configmap, configmap_error = safe_kube_json(["-n", NAMESPACE, "get", "configmap", configmap_name], f"configmap/{configmap_name}")
    state_cm, state_error = safe_kube_json(["-n", NAMESPACE, "get", "configmap", state_name], f"configmap/{state_name}")
    state = None
    if isinstance(state_cm, dict):
        raw_state = (state_cm.get("data") or {}).get("state.json")
        if isinstance(raw_state, str) and raw_state:
            try:
                state = json.loads(raw_state)
            except Exception as exc:
                state = {"parseError": str(exc)}
    accounts = (state.get("accounts") or {}) if isinstance(state, dict) else {}
    quarantined = []
    recent_accounts = []
    for name, account_state in accounts.items():
        if not isinstance(account_state, dict):
            continue
        quarantine = account_state.get("quarantine")
        if isinstance(quarantine, dict) and quarantine.get("active") is True:
            quarantined.append({
                "accountName": name,
                "until": quarantine.get("until"),
                "applied": quarantine.get("applied"),
                "reason": quarantine.get("reason"),
                "failureKind": quarantine.get("failureKind"),
                "errorDetails": quarantine.get("errorDetails"),
                "intervalMinutes": quarantine.get("intervalMinutes"),
                "sentinelProtect": quarantine.get("sentinelProtect"),
            })
        last_probe = account_state.get("lastProbe")
        if isinstance(last_probe, dict):
            recent_accounts.append({
                "accountName": name,
                "lastProbeAt": account_state.get("lastProbeAt"),
                "lastStatus": account_state.get("lastStatus"),
                "nextProbeAfter": account_state.get("nextProbeAfter"),
                "ok": last_probe.get("ok"),
                "purpose": last_probe.get("purpose"),
                "httpStatus": last_probe.get("httpStatus"),
                "durationMs": last_probe.get("durationMs"),
                "markerMatched": last_probe.get("markerMatched"),
                "sentinelProtect": last_probe.get("sentinelProtect") or account_state.get("sentinelProtectConfig"),
                "outputHash": last_probe.get("outputHash"),
                "outputPreview": last_probe.get("outputPreview"),
                "responseBodyHash": last_probe.get("responseBodyHash"),
                "responseBodyPreview": last_probe.get("responseBodyPreview"),
                "error": last_probe.get("error"),
                "errorDetails": last_probe.get("errorDetails"),
                "usage": last_probe.get("usage"),
                "failureKind": last_probe.get("failureKind"),
                "requestShape": last_probe.get("requestShape"),
                "action": last_probe.get("action"),
            })
    recent_accounts.sort(key=lambda item: item.get("lastProbeAt") or "")
    last_run = state.get("lastRun") if isinstance(state, dict) else None
    cronjob_spec = cronjob.get("spec") if isinstance(cronjob, dict) else {}
    secret_data = secret.get("data") if isinstance(secret, dict) else {}
    configmap_data = configmap.get("data") if isinstance(configmap, dict) else {}
    ok = cronjob is not None and secret is not None and configmap is not None
    return {
        "ok": ok,
        "desired": {
            "monitorEnabled": cfg.get("monitor", {}).get("enabled"),
            "actionsEnabled": cfg.get("actions", {}).get("enabled"),
            "schedule": cfg.get("schedule"),
            "cronJobName": cronjob_name,
            "configMapName": configmap_name,
            "credentialsSecretName": secret_name,
            "stateConfigMapName": state_name,
        },
        "cronJob": {
            "exists": cronjob is not None,
            "schedule": cronjob_spec.get("schedule") if isinstance(cronjob_spec, dict) else None,
            "suspend": cronjob_spec.get("suspend") if isinstance(cronjob_spec, dict) else None,
            "lastScheduleTime": (cronjob.get("status") or {}).get("lastScheduleTime") if isinstance(cronjob, dict) else None,
            "active": len((cronjob.get("status") or {}).get("active") or []) if isinstance(cronjob, dict) else None,
            "error": cronjob_error,
        },
        "secret": {
            "exists": secret is not None,
            "profileSecretPresent": isinstance(secret_data, dict) and "profiles.json" in secret_data,
            "valuesPrinted": False,
            "error": secret_error,
        },
        "configMap": {
            "exists": configmap is not None,
            "configPresent": isinstance(configmap_data, dict) and "config.json" in configmap_data,
            "runnerPresent": isinstance(configmap_data, dict) and "sentinel.py" in configmap_data,
            "error": configmap_error,
        },
        "state": {
            "exists": state_cm is not None,
            "accountCount": len(accounts),
            "quarantinedCount": len(quarantined),
            "quarantined": quarantined[-10:],
            "recentAccounts": recent_accounts[-12:],
            "lastRun": last_run,
            "error": state_error,
        },
        "valuesPrinted": False,
    }

def parse_epoch_z(value):
    if not isinstance(value, str) or not value:
        return None
    try:
        return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
    except Exception:
        return None

def sentinel_state_object():
    if not TARGET_SENTINEL_ENABLED:
        return None, None
    state_name = SENTINEL_CONFIG.get("stateConfigMapName")
    if not state_name:
        return None, None
    obj, err = safe_kube_json(["-n", NAMESPACE, "get", "configmap", state_name], f"configmap/{state_name}")
    if not isinstance(obj, dict):
        return None, None
    raw_state = (obj.get("data") or {}).get("state.json")
    if not isinstance(raw_state, str) or not raw_state:
        return obj, None
    try:
        return obj, json.loads(raw_state)
    except Exception:
        return obj, None

def active_sentinel_quarantine_names():
    if not TARGET_SENTINEL_ENABLED:
        return set()
    _, state = sentinel_state_object()
    if not isinstance(state, dict):
        return set()
    accounts_state = state.get("accounts") if isinstance(state.get("accounts"), dict) else {}
    names = set()
    for name, account_state in accounts_state.items():
        if not isinstance(name, str) or not isinstance(account_state, dict):
            continue
        quarantine = account_state.get("quarantine")
        if isinstance(quarantine, dict) and quarantine.get("active") is True and quarantine.get("applied") is True:
            names.add(name)
    return names

def default_sentinel_state():
    return {"version": 1, "accounts": {}, "ledger": {}, "history": []}

def clamp_sentinel_freezes_for_config(state, now):
    freeze_config = SENTINEL_CONFIG.get("freeze") if isinstance(SENTINEL_CONFIG.get("freeze"), dict) else {}
    try:
        max_interval = int(freeze_config.get("maxTtlMinutes") or 10)
    except Exception:
        max_interval = 10
    accounts_state = state.get("accounts") if isinstance(state.get("accounts"), dict) else {}
    now_epoch = time.time()
    items = []
    for name, account_state in accounts_state.items():
        if not isinstance(name, str) or not isinstance(account_state, dict):
            continue
        quarantine = account_state.get("quarantine")
        if not isinstance(quarantine, dict) or quarantine.get("active") is not True or quarantine.get("applied") is not True:
            continue
        try:
            interval = int(quarantine.get("intervalMinutes") or 0)
        except Exception:
            interval = 0
        until_epoch = parse_epoch_z(quarantine.get("until"))
        old_until = quarantine.get("until")
        if interval <= max_interval and (until_epoch is None or until_epoch <= now_epoch + max_interval * 60):
            continue
        quarantine["previousIntervalMinutes"] = interval
        quarantine["intervalMinutes"] = max_interval
        quarantine["until"] = now
        quarantine["clampedAt"] = now
        quarantine["clampedBy"] = "sync-freeze-max-ttl"
        account_state["nextProbeAfter"] = now
        items.append({
            "accountName": name,
            "previousIntervalMinutes": interval,
            "maxIntervalMinutes": max_interval,
            "previousUntil": old_until,
            "nextProbeAfter": now,
        })
    return items

def parse_iso_epoch(value):
    if not isinstance(value, str) or not value:
        return None
    try:
        return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
    except Exception:
        return None

def profile_success_max_interval(profile):
    cadence = SENTINEL_CONFIG.get("cadence") if isinstance(SENTINEL_CONFIG.get("cadence"), dict) else {}
    legacy = cadence.get("successMaxIntervalMinutes")
    if legacy is None:
        legacy = cadence.get("trustedSuccessMaxIntervalMinutes") or cadence.get("untrustedSuccessMaxIntervalMinutes") or 1
    if profile.get("trustUpstream") is True:
        value = cadence.get("trustedSuccessMaxIntervalMinutes") or legacy
    else:
        value = cadence.get("untrustedSuccessMaxIntervalMinutes") or legacy
    try:
        return int(value)
    except Exception:
        return int(legacy)

def clamp_sentinel_success_cadence_for_config(state, profiles, now):
    accounts_state = state.get("accounts") if isinstance(state.get("accounts"), dict) else {}
    profile_map = {item.get("accountName"): item for item in profiles if isinstance(item, dict) and isinstance(item.get("accountName"), str)}
    now_epoch = time.time()
    items = []
    for name, profile in profile_map.items():
        account_state = accounts_state.get(name)
        if not isinstance(account_state, dict):
            continue
        quarantine = account_state.get("quarantine")
        if isinstance(quarantine, dict) and quarantine.get("active") is True:
            account_state["trustUpstream"] = profile.get("trustUpstream") is True
            account_state["sentinelProtectConfig"] = profile.get("sentinelProtect") if isinstance(profile.get("sentinelProtect"), dict) else {"enabled": False}
            account_state["successMaxIntervalMinutes"] = profile_success_max_interval(profile)
            continue
        try:
            interval = int(account_state.get("successIntervalMinutes") or 0)
        except Exception:
            interval = 0
        next_epoch = parse_iso_epoch(account_state.get("nextProbeAfter"))
        max_interval = profile_success_max_interval(profile)
        account_state["trustUpstream"] = profile.get("trustUpstream") is True
        account_state["sentinelProtectConfig"] = profile.get("sentinelProtect") if isinstance(profile.get("sentinelProtect"), dict) else {"enabled": False}
        account_state["successMaxIntervalMinutes"] = max_interval
        if interval <= max_interval and (next_epoch is None or next_epoch <= now_epoch + max_interval * 60):
            continue
        old_next = account_state.get("nextProbeAfter")
        account_state["previousSuccessIntervalMinutes"] = interval
        account_state["successIntervalMinutes"] = min(interval, max_interval) if interval > 0 else interval
        account_state["nextProbeAfter"] = now
        account_state["cadenceClampedAt"] = now
        account_state["cadenceClampedBy"] = "sync-success-max-interval"
        items.append({
            "accountName": name,
            "trustUpstream": profile.get("trustUpstream") is True,
            "previousSuccessIntervalMinutes": interval,
            "maxIntervalMinutes": max_interval,
            "previousNextProbeAfter": old_next,
            "nextProbeAfter": now,
        })
    return items

def update_sentinel_state_configmap(obj, state):
    state_name = SENTINEL_CONFIG.get("stateConfigMapName")
    if not state_name:
        return {"ok": False, "reason": "state-configmap-missing"}
    state_json = json.dumps(state, ensure_ascii=False, indent=2)
    manifest = {
        "apiVersion": "v1",
        "kind": "ConfigMap",
        "metadata": {
            "name": state_name,
            "namespace": NAMESPACE,
            "labels": {
                "app.kubernetes.io/name": SERVICE_NAME,
                "app.kubernetes.io/component": "account-sentinel",
                "app.kubernetes.io/managed-by": "unidesk-platform-infra",
            },
        },
        "data": {"state.json": state_json},
    }
    proc = kubectl(["apply", "--server-side", "--force-conflicts", f"--field-manager={FIELD_MANAGER}", "-f", "-"], json.dumps(manifest))
    action = "applied" if isinstance(obj, dict) else "created"
    if proc.returncode != 0:
        return {"ok": False, "reason": f"{action}-failed", "stderrTail": text(proc.stderr, 2000)}
    return {"ok": True, "action": action}

def ensure_sentinel_state_for_sync(account_results, pending_only=False):
    if not sentinel_quality_gate_enabled():
        return {"ok": True, "skipped": True, "reason": "sentinel-quality-gate-disabled", "changedCount": 0, "items": [], "valuesPrinted": False}
    state_obj, state = sentinel_state_object()
    if not isinstance(state, dict):
        state = default_sentinel_state()
    state.setdefault("version", 1)
    accounts_state = state.setdefault("accounts", {})
    if not isinstance(accounts_state, dict):
        accounts_state = {}
        state["accounts"] = accounts_state
    now = utc_iso()
    items = []
    clamped_items = [] if pending_only else clamp_sentinel_freezes_for_config(state, now)
    cadence_clamped_items = [] if pending_only else clamp_sentinel_success_cadence_for_config(state, [item.get("profileConfig") for item in account_results if isinstance(item.get("profileConfig"), dict)], now)
    changed_count = 0
    fingerprint_only_count = 0
    for item in account_results:
        name = item.get("accountName")
        if not isinstance(name, str) or not name:
            continue
        account_state = accounts_state.setdefault(name, {})
        if not isinstance(account_state, dict):
            account_state = {}
            accounts_state[name] = account_state
        fingerprint_value = item.get("sentinelProbeConfigFingerprint")
        if isinstance(fingerprint_value, str) and fingerprint_value:
            account_state["probeConfigFingerprint"] = fingerprint_value
        if item.get("sentinelProbeRequired") is not True:
            fingerprint_only_count += 1
            continue
        changed_count += 1
        reasons = item.get("sentinelChangeReasons") if isinstance(item.get("sentinelChangeReasons"), list) else []
        quarantine = account_state.get("quarantine") if isinstance(account_state.get("quarantine"), dict) else None
        if not (isinstance(quarantine, dict) and quarantine.get("active") is True):
            account_state["quarantine"] = {
                "active": False,
                "reason": "yaml-account-change-pending-sentinel-probe",
                "lastPendingAt": now,
                "changeReasons": reasons,
            }
        account_state["nextProbeAfter"] = now
        account_state["successStreak"] = 0
        account_state["successIntervalMinutes"] = 0
        profile_config = item.get("profileConfig") if isinstance(item.get("profileConfig"), dict) else {}
        account_state["trustUpstream"] = profile_config.get("trustUpstream") is True
        account_state["sentinelProtectConfig"] = profile_config.get("sentinelProtect") if isinstance(profile_config.get("sentinelProtect"), dict) else {"enabled": False}
        account_state["successMaxIntervalMinutes"] = profile_success_max_interval(profile_config)
        account_state["lastStatus"] = "pending-sentinel-quality-gate"
        account_state["qualityGate"] = {
            "pending": True,
            "reason": "yaml-account-change",
            "changeReasons": reasons,
            "markedAt": now,
            "pendingOnly": pending_only,
            "defaultFrozen": False,
        }
        items.append({"accountName": name, "changeReasons": reasons, "nextProbeAfter": now, "defaultFrozen": False, "defaultSchedulable": True, "pendingOnly": pending_only})
    if changed_count <= 0 and len(clamped_items) <= 0 and len(cadence_clamped_items) <= 0:
        return {"ok": True, "skipped": False, "reason": "no-new-or-changed-accounts", "changedCount": 0, "fingerprintOnlyCount": fingerprint_only_count, "clampedCount": 0, "cadenceClampedCount": 0, "items": [], "valuesPrinted": False}
    update = update_sentinel_state_configmap(state_obj, state)
    if pending_only and changed_count > 0:
        reason = "new-or-changed-accounts-pending-probe-prepared-default-schedulable"
    elif changed_count > 0 and (len(clamped_items) > 0 or len(cadence_clamped_items) > 0):
        reason = "new-or-changed-accounts-default-schedulable-and-sentinel-cadence-clamped"
    elif changed_count > 0:
        reason = "new-or-changed-accounts-default-schedulable"
    elif len(cadence_clamped_items) > 0:
        reason = "success-cadence-clamped-to-current-config"
    else:
        reason = "freeze-backoff-clamped-to-current-config"
    return {
        "ok": update.get("ok") is True,
        "skipped": False,
        "reason": reason,
        "changedCount": changed_count,
        "fingerprintOnlyCount": fingerprint_only_count,
        "clampedCount": len(clamped_items),
        "cadenceClampedCount": len(cadence_clamped_items),
        "pendingOnly": pending_only,
        "items": items,
        "clampedItems": clamped_items,
        "cadenceClampedItems": cadence_clamped_items,
        "update": update,
        "valuesPrinted": False,
    }

def sentinel_state_summary():
    _, state = sentinel_state_object()
    if not isinstance(state, dict):
        return {"exists": False, "valuesPrinted": False}
    accounts = state.get("accounts") if isinstance(state.get("accounts"), dict) else {}
    quarantined = []
    recent_accounts = []
    for name, account_state in accounts.items():
        if not isinstance(account_state, dict):
            continue
        quarantine = account_state.get("quarantine")
        if isinstance(quarantine, dict) and quarantine.get("active") is True:
            quarantined.append({
                "accountName": name,
                "until": quarantine.get("until"),
                "applied": quarantine.get("applied"),
                "reason": quarantine.get("reason"),
                "failureKind": quarantine.get("failureKind"),
                "errorDetails": quarantine.get("errorDetails"),
                "intervalMinutes": quarantine.get("intervalMinutes"),
                "sentinelProtect": quarantine.get("sentinelProtect"),
            })
        last_probe = account_state.get("lastProbe")
        if isinstance(last_probe, dict):
            recent_accounts.append({
                "accountName": name,
                "lastProbeAt": account_state.get("lastProbeAt"),
                "lastStatus": account_state.get("lastStatus"),
                "nextProbeAfter": account_state.get("nextProbeAfter"),
                "ok": last_probe.get("ok"),
                "purpose": last_probe.get("purpose"),
                "httpStatus": last_probe.get("httpStatus"),
                "durationMs": last_probe.get("durationMs"),
                "markerMatched": last_probe.get("markerMatched"),
                "sentinelProtect": last_probe.get("sentinelProtect") or account_state.get("sentinelProtectConfig"),
                "usage": last_probe.get("usage"),
                "responseBodyHash": last_probe.get("responseBodyHash"),
                "responseBodyPreview": last_probe.get("responseBodyPreview"),
                "error": last_probe.get("error"),
                "errorDetails": last_probe.get("errorDetails"),
                "failureKind": last_probe.get("failureKind"),
                "requestShape": last_probe.get("requestShape"),
                "action": last_probe.get("action"),
            })
    recent_accounts.sort(key=lambda item: item.get("lastProbeAt") or "")
    return {
        "exists": True,
        "accountCount": len(accounts),
        "quarantinedCount": len(quarantined),
        "quarantined": quarantined[-10:],
        "recentAccounts": recent_accounts[-12:],
        "lastRun": state.get("lastRun"),
        "valuesPrinted": False,
    }

def reassert_sentinel_freezes_after_sync(token):
    if not TARGET_SENTINEL_ENABLED:
        return {"ok": True, "skipped": True, "reason": "target-disabled", "items": [], "valuesPrinted": False}
    if (SENTINEL_CONFIG.get("actions") or {}).get("enabled") is not True:
        return {"ok": True, "skipped": True, "reason": "actions-disabled", "items": [], "valuesPrinted": False}
    _, state = sentinel_state_object()
    if not isinstance(state, dict):
        return {"ok": True, "skipped": True, "reason": "state-missing", "items": [], "valuesPrinted": False}
    accounts_state = state.get("accounts") if isinstance(state.get("accounts"), dict) else {}
    accounts = list_accounts(token)
    by_name = {item.get("name"): item for item in accounts if isinstance(item.get("name"), str)}
    items = []
    for name, account_state in accounts_state.items():
        if not isinstance(account_state, dict):
            continue
        quarantine = account_state.get("quarantine")
        if not isinstance(quarantine, dict) or quarantine.get("active") is not True or quarantine.get("applied") is not True:
            continue
        account = by_name.get(name)
        if not account or account.get("id") is None:
            items.append({"accountName": name, "ok": False, "reason": "account-not-found"})
            continue
        try:
            ensure_success(
                curl_api("POST", f"/api/v1/admin/accounts/{account['id']}/schedulable", bearer=token, payload={"schedulable": False}),
                f"reassert sentinel freeze for {name}",
            )
            items.append({"accountName": name, "accountId": account.get("id"), "ok": True, "until": quarantine.get("until")})
        except Exception as exc:
            items.append({"accountName": name, "accountId": account.get("id"), "ok": False, "error": str(exc)})
    return {
        "ok": all(item.get("ok") is True for item in items),
        "skipped": False,
        "items": items,
        "valuesPrinted": False,
    }

def list_user_keys(token):
    data = ensure_success(curl_api("GET", "/api/v1/keys?page=1&page_size=200", bearer=token), "list user keys")
    return extract_items(data)

def ensure_sub2api_api_key(token, api_key, group_id):
    keys = list_user_keys(token)
    existing = next((item for item in keys if item.get("key") == api_key), None)
    action = "kept-existing"
    if existing is None:
        existing = next((item for item in keys if item.get("name") == POOL_API_KEY_NAME), None)
    if existing is None or existing.get("key") != api_key:
        payload = {
            "name": POOL_API_KEY_NAME,
            "group_id": group_id,
            "custom_key": api_key,
            "quota": 0,
            "rate_limit_5h": 0,
            "rate_limit_1d": 0,
            "rate_limit_7d": 0,
        }
        created = ensure_success(curl_api("POST", "/api/v1/keys", bearer=token, payload=payload), "create pool API key")
        existing = created if isinstance(created, dict) else existing
        action = "created"
    elif existing.get("id") is not None and (existing.get("group_id") != group_id or existing.get("name") != POOL_API_KEY_NAME):
        updated = ensure_success(curl_api("PUT", f"/api/v1/keys/{existing['id']}", bearer=token, payload={"name": POOL_API_KEY_NAME, "group_id": group_id}), "update pool API key group")
        existing = updated if isinstance(updated, dict) else existing
        action = "updated-name-group"
    return {
        "action": action,
        "id": existing.get("id") if isinstance(existing, dict) else None,
        "name": existing.get("name") if isinstance(existing, dict) else POOL_API_KEY_NAME,
        "groupId": existing.get("group_id") if isinstance(existing, dict) else group_id,
        "userId": existing.get("user_id") if isinstance(existing, dict) else None,
    }

def get_admin_user(token, user_id):
    data = ensure_success(curl_api("GET", f"/api/v1/admin/users/{user_id}", bearer=token), "get API key owner")
    if not isinstance(data, dict):
        raise RuntimeError("API key owner response is not an object")
    return data

def ensure_pool_owner_balance(token, user_id):
    user = get_admin_user(token, user_id)
    current = float(user.get("balance") or 0)
    if current >= MIN_OWNER_BALANCE_USD:
        return {
            "action": "kept-existing",
            "userId": user_id,
            "balanceBefore": current,
            "balanceAfter": current,
            "minimumBalanceUsd": MIN_OWNER_BALANCE_USD,
        }
    updated = ensure_success(curl_api("POST", f"/api/v1/admin/users/{user_id}/balance", bearer=token, payload={
        "balance": MIN_OWNER_BALANCE_USD,
        "operation": "set",
        "notes": "UniDesk Sub2API Codex pool internal API key bootstrap balance.",
    }), "set API key owner balance")
    after = float(updated.get("balance") or MIN_OWNER_BALANCE_USD) if isinstance(updated, dict) else MIN_OWNER_BALANCE_USD
    return {
        "action": "set",
        "userId": user_id,
        "balanceBefore": current,
        "balanceAfter": after,
        "minimumBalanceUsd": MIN_OWNER_BALANCE_USD,
    }

def ensure_pool_owner_concurrency(token, user_id):
    user = get_admin_user(token, user_id)
    try:
        current = int(user.get("concurrency") or 0)
    except Exception:
        current = 0
    if current >= MIN_OWNER_CONCURRENCY:
        return {
            "ok": True,
            "action": "kept-existing",
            "userId": user_id,
            "concurrencyBefore": current,
            "concurrencyAfter": current,
            "minimumConcurrency": MIN_OWNER_CONCURRENCY,
            "minimumConcurrencySource": MIN_OWNER_CONCURRENCY_SOURCE,
        }
    updated = ensure_success(curl_api("PUT", f"/api/v1/admin/users/{user_id}", bearer=token, payload={
        "concurrency": MIN_OWNER_CONCURRENCY,
    }), "set API key owner concurrency")
    try:
        after = int(updated.get("concurrency") or MIN_OWNER_CONCURRENCY) if isinstance(updated, dict) else MIN_OWNER_CONCURRENCY
    except Exception:
        after = MIN_OWNER_CONCURRENCY
    return {
        "ok": after >= MIN_OWNER_CONCURRENCY,
        "action": "set",
        "userId": user_id,
        "concurrencyBefore": current,
        "concurrencyAfter": after,
        "minimumConcurrency": MIN_OWNER_CONCURRENCY,
        "minimumConcurrencySource": MIN_OWNER_CONCURRENCY_SOURCE,
    }

`;
