import { assertAccountActive } from "../account-disable";
import { captureServerEvent } from "../analytics";
import { accountDb, repoDb, type ScopedDb } from "../scoped-db";
import { forgetLocator, locate, registerLocator } from "../scoped-db/locators";
import { scopedId } from "../scoped-db/ids";
import { ownerRepoIds, repoOwnerId, runnerDb } from "./scope";
import { randomToken, sha256Hex } from "../crypto";
import { assertBelowCap, CAPS } from "../limits";
import { forbidden, HttpError } from "../errors";
import { canAdministerAccount } from "../repos";
import { runnerStub } from "./jobs";
import { failStrandedForkJobs } from "./runner-policy";
import type { RepoRow, Viewer } from "~/lib/types";
export const RUNNER_TOKEN_PREFIX = "gitfor_runner";
export const REGISTRATION_TOKEN_PREFIX = "gitfor_reg";
export const REGISTRATION_TTL_MS = 60 * 60 * 1000;
/** A rotated-out credential keeps working this long, or until the new one has been used for a while. */
export const ROTATION_GRACE_MS = 60 * 60 * 1000;
/** Once the new credential is used, requests already in flight on the old one still get this long. */
const CONFIRMED_GRACE_MS = 5 * 60 * 1000;
const TOKEN_HASH = /^[0-9a-f]{64}$/;
/** Credentials older than this are asked to rotate on their next request. */
export const ROTATE_AFTER_MS = 24 * 60 * 60 * 1000;
export const ONLINE_WINDOW_MS = 2 * 60 * 1000;
export const MAX_RUNNER_JOBS = 16;
const MAX_LABELS = 20;
const MAX_PENDING_REGISTRATIONS = 20;
const LABEL = /^[a-z0-9][a-z0-9._-]{0,31}$/;
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
const OS_VALUES = new Set(["linux", "macos", "windows", "freebsd"]);
const ARCH_VALUES = new Set(["x64", "arm64", "arm", "x86"]);
const ISOLATION_VALUES = new Set(["docker", "podman", "none"]);
export type RunnerScope = { kind: "repository"; repoId: string } | { kind: "owner"; ownerId: string };
export type RunnerRow = {
id: string;
repo_id: string | null;
owner_id: string | null;