export const remotePythonSentinelProbeScript = `def parse_embedded_json(stdout):
    if not isinstance(stdout, str) or not stdout.strip():
        return None
    start = stdout.find("{")
    end = stdout.rfind("}")
    if start < 0 or end <= start:
        return None
    try:
        return json.loads(stdout[start:end + 1])
    except Exception:
        return None

def inject_env(template, name, value):
    spec = template.setdefault("spec", {})
    containers = spec.setdefault("containers", [])
    if not containers:
        raise RuntimeError("sentinel job template has no containers")
    container = containers[0]
    env = container.setdefault("env", [])
    env[:] = [item for item in env if not (isinstance(item, dict) and item.get("name") == name)]
    env.append({"name": name, "value": value})

def sentinel_probe_job_manifest(accounts):
    cronjob_name = SENTINEL_CONFIG.get("cronJobName")
    if not isinstance(cronjob_name, str) or not cronjob_name:
        raise RuntimeError("sentinel cronJobName missing from config")
    cronjob = kube_json(["-n", NAMESPACE, "get", "cronjob", cronjob_name], f"cronjob/{cronjob_name}")
    job_template = ((cronjob.get("spec") or {}).get("jobTemplate") or {}) if isinstance(cronjob, dict) else {}
    job_spec = copy_json(job_template.get("spec") or {})
    if not isinstance(job_spec, dict) or not job_spec:
        raise RuntimeError("sentinel CronJob jobTemplate.spec missing")
    template = job_spec.get("template")
    if not isinstance(template, dict):
        raise RuntimeError("sentinel CronJob jobTemplate.spec.template missing")
    inject_env(template, "SENTINEL_ACCOUNT_NAMES", ",".join(accounts))
    job_spec["ttlSecondsAfterFinished"] = int(job_spec.get("ttlSecondsAfterFinished") or 3600)
    suffix = str(int(time.time()))[-8:] + "-" + "".join(secrets.choice(string.ascii_lowercase + string.digits) for _ in range(5))
    job_name = ("sub2api-sentinel-probe-" + suffix)[:63]
    return job_name, {
        "apiVersion": "batch/v1",
        "kind": "Job",
        "metadata": {
            "name": job_name,
            "namespace": NAMESPACE,
            "labels": {
                "app.kubernetes.io/name": cronjob_name,
                "app.kubernetes.io/part-of": "platform-infra",
                "app.kubernetes.io/managed-by": "unidesk",
                "unidesk.ai/job-purpose": "sub2api-account-sentinel-manual-probe",
            },
        },
        "spec": job_spec,
    }

def copy_json(value):
    return json.loads(json.dumps(value))

def job_condition(job, cond_type):
    for item in ((job.get("status") or {}).get("conditions") or []):
        if item.get("type") == cond_type and item.get("status") == "True":
            return item
    return None

def wait_sentinel_probe_job(job_name, timeout_seconds):
    deadline = time.time() + timeout_seconds
    latest = None
    while time.time() < deadline:
        latest, err = safe_kube_json(["-n", NAMESPACE, "get", "job", job_name], f"job/{job_name}")
        if isinstance(latest, dict):
            complete = job_condition(latest, "Complete")
            failed = job_condition(latest, "Failed")
            if complete is not None:
                return "succeeded", latest, complete
            if failed is not None:
                return "failed", latest, failed
        time.sleep(2)
    return "timeout", latest, None

def job_logs(job_name):
    proc = kubectl(["-n", NAMESPACE, "logs", f"job/{job_name}", "--tail=4000"])
    return {
        "exitCode": proc.returncode,
        "stdout": proc.stdout.decode("utf-8", errors="replace"),
        "stderr": text(proc.stderr, 4000),
    }

def run_sentinel_probe():
    payload = json.loads(base64.b64decode(PAYLOAD_B64).decode("utf-8")) if PAYLOAD_B64 else {}
    accounts = payload.get("accounts") if isinstance(payload, dict) else None
    if not isinstance(accounts, list) or not accounts or not all(isinstance(item, str) and item for item in accounts):
        raise RuntimeError("sentinel-probe payload requires non-empty accounts")
    job_name, manifest = sentinel_probe_job_manifest(accounts)
    proc = kubectl(["apply", "--server-side", "--force-conflicts", f"--field-manager={FIELD_MANAGER}", "-f", "-"], json.dumps(manifest))
    if proc.returncode != 0:
        raise RuntimeError(f"apply sentinel probe job failed: {text(proc.stderr, 2000)}")
    timeout_seconds = max(300, int(SENTINEL_CONFIG.get("probe", {}).get("timeoutSeconds") or 30) + 240)
    status, job, condition = wait_sentinel_probe_job(job_name, timeout_seconds)
    logs = job_logs(job_name)
    parsed = parse_embedded_json(logs.get("stdout") or "")
    results = parsed.get("results") if isinstance(parsed, dict) and isinstance(parsed.get("results"), list) else []
    state_summary = sentinel_state_summary()
    last_run = state_summary.get("lastRun") if isinstance(state_summary, dict) and isinstance(state_summary.get("lastRun"), dict) else {}
    if not results and isinstance(last_run.get("results"), list):
        results = last_run.get("results")
    requested = set(accounts)
    measured = {item.get("accountName") for item in results if isinstance(item, dict)}
    missing = sorted(name for name in requested if name not in measured)
    marker_ok = len(missing) == 0 and all(isinstance(item, dict) and item.get("accountName") in requested and item.get("markerMatched") is True for item in results if isinstance(item, dict) and item.get("accountName") in requested)
    if not results and isinstance(last_run, dict):
        selected = int(last_run.get("selected") or 0)
        ok_count = int(last_run.get("okCount") or 0)
        marker_mismatch_count = int(last_run.get("markerMismatchCount") or 0)
        transport_failure_count = int(last_run.get("transportFailureCount") or 0)
        if selected >= len(requested) and ok_count >= len(requested) and marker_mismatch_count == 0 and transport_failure_count == 0:
            missing = []
            marker_ok = True
    job_ok = status == "succeeded" and logs.get("exitCode") == 0
    return {
        "ok": job_ok and marker_ok,
        "jobExecutionOk": job_ok,
        "markerOk": marker_ok,
        "mode": "sentinel-probe",
        "namespace": NAMESPACE,
        "requestedAccounts": accounts,
        "missingAccounts": missing,
        "job": {
            "name": job_name,
            "status": status,
            "condition": condition,
            "timeoutSeconds": timeout_seconds,
            "applyStdoutTail": text(proc.stdout, 1200),
            "logsExitCode": logs.get("exitCode"),
            "logsStderrTail": logs.get("stderr"),
        },
        "probe": parsed,
        "summary": {
            "at": last_run.get("at"),
            "selected": last_run.get("selected"),
            "okCount": last_run.get("okCount"),
            "markerMismatchCount": last_run.get("markerMismatchCount"),
            "transportFailureCount": last_run.get("transportFailureCount"),
            "actionsTaken": last_run.get("actionsTaken"),
            "selection": last_run.get("selection"),
        },
        "results": results,
        "sentinelState": state_summary,
        "valuesPrinted": False,
    }

def run_cleanup_probes():
    admin_email, token, admin_compliance = login()
    cleanup = cleanup_probe_resources(token)
    return {
        "ok": cleanup.get("ok") is True,
        "mode": "cleanup-probes",
        "namespace": NAMESPACE,
        "serviceDns": SERVICE_DNS,
        "appPod": APP_POD,
        "admin": {"email": admin_email, "tokenPrinted": False, "compliance": admin_compliance},
        "cleanup": cleanup,
        "valuesPrinted": False,
    }

try:
    if MODE == "sync":
        result = run_sync()
    elif MODE == "trace":
        result = run_trace()
    elif MODE == "cleanup-probes":
        result = run_cleanup_probes()
    elif MODE == "sentinel-probe":
        result = run_sentinel_probe()
    elif MODE == "profit":
        result = run_profit_report()
    elif MODE == "credits":
        result = run_credits_grant()
    elif MODE == "announcements":
        result = run_announcements()
    else:
        result = run_validate()
except Exception as exc:
    result = {
        "ok": False,
        "mode": MODE,
        "namespace": NAMESPACE,
        "serviceDns": SERVICE_DNS,
        "appPod": globals().get("APP_POD"),
        "error": str(exc),
        "valuesPrinted": False,
    }

print(json.dumps(result, ensure_ascii=False, indent=2))
sys.exit(0 if result.get("ok") else 1)
PY
`;
