import { configuredAnthropicInstance, isAnthropicOAuthInstance } from "../providers/anthropic-instance";
import { parseQuotaFailureCode, parseQuotaUnknownReason, type QuotaFailureCode, type QuotaUnknownReason, type ProviderQuota, type AccountQuotaMode } from "../providers/quota-types";
import { parseWeeklyWindowConflicts, type WeeklyWindowConflict } from "../codex/quota-window-conflict";
/**
 * Data-access layer for `ocx account` (issue #180) — live-proxy HTTP client and
 * per-family account readers. Kept separate from account.ts (command handlers)
 * per the 400-line module budget.
 */
import { findLiveProxy, probeHostname } from "../server/proxy-liveness";
import { runningProxyUpdateHeaders } from "../oauth/login-cli";
import { isPublicOAuthProvider } from "../oauth/index";
import { getProviderRegistryEntry, providerCodexAccountMode } from "../providers/registry";
import type { OcxConfig } from "../types";
import { projectCodexQuotaRefreshOutcome, type CodexQuotaRefreshOutcome } from "../codex/quota-refresh-outcome";

import { projectApiKeyQuotaRows } from "./account-key-quota";
import { projectAccountHealth } from "./account-next-actions";
import type { OAuthHealthLabel } from "../oauth/health";

import { accountPauseDetailsSchema } from "../config/schema/account-auto-pause";
export type AccountType = "codex" | "oauth" | "api-key";

export interface AccountRow {
  provider: string;
  type: AccountType;
  id: string;
  slotId?: string;
  slotKind?: "native-main" | "pool";
  upstreamAccountKey?: string;
  label?: string;
  email?: string;
  /**
   * Subscription tier. `null` means this version looked and the provider did not report one;
   * an absent key means the row's surface does not carry a tier at all (#3777).
   */
  plan?: string | null;
  masked?: string;
  active: boolean;
  needsReauth?: boolean;
  /** Validated server health label and locally generated recovery guidance. */
  health?: OAuthHealthLabel;
  healthAction?: string;
  /** Explicit paid-credit consent, reported only when supplied by the Codex API. */
  creditsAfterLimit?: boolean;
  needsReauthReason?: "verify_account";
  needsReauthCause?: "tos_violation";
  autoSelectable?: boolean;
  skipReason?: "paused" | "needs_reauth" | "suspended" | "cooldown" | "quota_exhausted";
  selectionExcludedReason?: "plan_excluded";
  selectionExcludedPlan?: string;
  /** Registered credential that is still excluded from routing until validation completes. */
  validationPending?: boolean;
  /** Codex pool selection order, higher used earlier. Absent where ordering does not apply. */
  priority?: number;
  /** Null means the account inherits the global usage-switch threshold. */
  autoSwitchThresholdOverride?: number | null;
  quota?: (CodexQuotaDto & Partial<ProviderQuota>) | null;
  quotaMode?: AccountQuotaMode;
  quotaRefresh?: CodexQuotaRefreshOutcome;
  quotaUnavailable?: boolean;
  quotaFailure?: QuotaFailureCode;
  /** Live weekly windows a Codex pool account reported in contradiction (#8574). */
  weeklyQuotaConflicts?: WeeklyWindowConflict[];
  /** Why the balance is unknown (#8397); reasons this CLI does not know are dropped. */
  quotaUnknownReason?: QuotaUnknownReason;
  /** When the server last read this balance, success or failure (epoch ms). */
  quotaReadAt?: number;
  /**
   * Whether the pool is holding this account out of rotation.
   *
   * The server has always sent it (auth-api.ts:286 for pool accounts, :1315 for main) and the
   * CLI dropped it, so a paused account was indistinguishable from an available one in every
   * human listing (#2703).
   */
  paused?: boolean;
  pauseDetails?: import("../types/account-auto-pause").AccountPauseDetails;
}

export type ClassifyResult = { type: AccountType } | { error: string };

export type AccountStdin = NodeJS.ReadableStream & { isTTY?: boolean };

export interface NativeMainLoginChild {
  exited: Promise<number>;
  kill(signal?: number | NodeJS.Signals): void;
}

export interface StageLeaseClock {
  now(): number;
  setTimeout(callback: () => void, ms: number): ReturnType<typeof setTimeout>;
  clearTimeout(timer: ReturnType<typeof setTimeout>): void;
}

import type { AntigravityRiskSeams } from "../oauth/antigravity-risk";

export interface AccountDeps {
  /** Test seams for the Google Antigravity acknowledgement (agent detection, prompt visibility). */
  antigravityRisk?: AntigravityRiskSeams;
  /** Test injection: skip findLiveProxy and call the API at this base URL. */
  baseUrl?: string;
  fetchImpl?: typeof fetch;
  loadConfigImpl?: () => OcxConfig;
  stdinImpl?: AccountStdin;
  stdinTimeoutMs?: number;
  /** Internal test seam for the account-import POST; production is capped at ten minutes. */
  importTimeoutMs?: number;
  /** Test/platform injection for the official Codex login in a restricted staging home. */
  spawnCodexLoginImpl?: (codexHome: string) => NativeMainLoginChild;
  /** Legacy test seam. Production always uses the spawned child handle above. */
  runCodexLoginImpl?: (codexHome: string) => Promise<number>;
  /** Test-only heartbeat cadence floor. Production keeps the five-second floor. */
  stageHeartbeatIntervalMinMs?: number;
  /** Test-only clock for deterministic native-profile lease deadline coverage. */
  stageLeaseClock?: StageLeaseClock;
}

export function classifyAccount(config: OcxConfig, name: string): ClassifyResult {
  const provider = config.providers?.[name];
  if (providerCodexAccountMode(name, provider)) return { type: "codex" };
  const entry = getProviderRegistryEntry(name);
  if (entry?.authKind === "local") {
    return { error: `provider "${name}" is a local provider and has no credentials` };
  }
  if (provider?.authMode === "forward") {
    return { error: `provider "${name}" uses forward auth and has no switchable credentials` };
  }
  if (provider?.authMode === "key") return { type: "api-key" };
  if (provider && !provider.authMode && (provider.apiKey || (provider.apiKeyPool?.length ?? 0) > 0)) {
    return { type: "api-key" };
  }
  if (name === "anthropic2" && !configuredAnthropicInstance(config, name)) return { error: "Anthropic pool instance is not configured" };
  if (isPublicOAuthProvider(name)) return { type: "oauth" };
  if (provider) return { type: "api-key" };
  return { error: `unknown provider "${name}"` };
}

export interface ApiResult {
  /** 0 = network-level failure (proxy unreachable). */
  status: number;
  json: Record<string, unknown>;
  /**
   * Message from the thrown transport error when `status` is 0. Previously the
   * error was swallowed by a catch block with an empty body, so an unreachable proxy, a DNS
   * failure and a TLS error were indistinguishable (#2698).
   */
  transportError?: string;
}

export async function apiJson(
  deps: AccountDeps,
  baseUrl: string,
  method: "GET" | "PUT" | "POST" | "DELETE",
  path: string,
  body?: unknown,
  options: { signal?: AbortSignal; redirect?: RequestRedirect } = {},
): Promise<ApiResult> {
  if (baseUrl === LINK_HOME_BASE) return linkHomeApiJson(deps, method, path);
  const fetchImpl = deps.fetchImpl ?? fetch;
  try {
    const res = await fetchImpl(`${baseUrl}${path}`, {
      method,
      headers: runningProxyUpdateHeaders(),
      body: body === undefined ? undefined : JSON.stringify(body),
      signal: options.signal,
      ...(options.redirect ? { redirect: options.redirect } : {}),
    });
    const json = (await res.json().catch(() => ({}))) as Record<string, unknown>;
    return { status: res.status, json };
  } catch (error) {
    // status 0 stays the transport sentinel, but keep the cause: callers can now
    // tell the operator why the request never reached the proxy (#2698).
    return {
      status: 0,
      json: {},
      transportError: error instanceof Error ? error.message : String(error),
    };
  }
}

export async function resolveBaseUrl(deps: AccountDeps): Promise<string | null> {
  if (deps.baseUrl) return deps.baseUrl;
  const live = await findLiveProxy();
  if (!live) return null;
  if (live.role === "client") {
    const { readLinkChildContext } = await import("./link-child");
    if (readLinkChildContext()) return LINK_HOME_BASE;
  }
  return `http://${probeHostname(live.hostname)}:${live.port}`;
}

/**
 * Remote Link Child (#6957): account reads come from the Home over the link, and every account
 * change is refused with the Child refusal. The marker is never a URL and never reaches fetch.
 */
export const LINK_HOME_BASE = "ocx-link-home:";

async function linkHomeApiJson(deps: AccountDeps, method: string, path: string): Promise<ApiResult> {
  const { readLinkChildContext, linkChildReadable, linkChildRefusal, readLinkHomeJson } = await import("./link-child");
  const link = readLinkChildContext();
  if (!link) return { status: 503, json: { error: "The Remote Link connection changed while the command ran; retry." } };
  const pathname = new URL(path, "http://cli.invalid").pathname;
  if (!linkChildReadable(method, path)) {
    return { status: 403, json: { error: linkChildRefusal(link, `${method} ${pathname}`) } };
  }
  try {
    const { status, body } = await readLinkHomeJson(link, path, deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {});
    return { status, json: (body && typeof body === "object" ? body : { error: String(body ?? "") }) as Record<string, unknown> };
  } catch (error) {
    return { status: 503, json: { error: error instanceof Error ? error.message : String(error) } };
  }
}

/**
 * The config account commands classify providers against. On a Remote Link Child the local
 * providers are inactive, so the Home's `/api/providers` projection (presence flags only) takes
 * their place. Anywhere else the local config is returned. When the Home cannot be read the
 * result is an error: classifying against the inactive local providers would answer for the
 * wrong machine.
 */
export async function accountClassificationConfig(
  deps: AccountDeps,
  local: OcxConfig,
): Promise<{ config: OcxConfig } | { error: string }> {
  if (deps.baseUrl) return { config: local };
  const { readLinkChildContext, readLinkHomeJson } = await import("./link-child");
  const link = readLinkChildContext();
  if (!link) return { config: local };
  const unavailable = (detail: string) => ({ error: `Could not read the provider list from ${link.homePhrase} over Remote Link (${link.linkId}): ${detail}.` });
  try {
    const { status, body } = await readLinkHomeJson(link, "/api/providers", deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {});
    if (status !== 200) {
      // Keep the Home's own sentence (for example the upgrade instruction an older Home yields).
      const message = body && typeof body === "object" && typeof (body as { error?: unknown }).error === "string"
        ? (body as { error: string }).error : null;
      return unavailable(message ?? `the Home answered HTTP ${status}`);
    }
    if (!Array.isArray(body)) return unavailable("the Home returned an unreadable provider list");
    const providers: Record<string, unknown> = {};
    for (const row of body) {
      if (!row || typeof row !== "object" || typeof (row as { name?: unknown }).name !== "string") continue;
      const { name, hasApiKey, ...rest } = row as Record<string, unknown> & { name: string };
      // A placeholder marks presence for classification; no credential value crosses the link.
      providers[name] = { ...rest, ...(hasApiKey === true ? { apiKey: "home-credential" } : {}) };
    }
    return { config: { ...local, providers: providers as OcxConfig["providers"] } };
  } catch (error) {
    return { error: error instanceof Error ? error.message : String(error) };
  }
}

export function proxyUnreachable(transportError?: string): number {
  console.error("Proxy not reachable. Start it with 'ocx start' or 'ocx ensure'.");
  // Naming the transport cause distinguishes "nothing is listening" from a refused
  // or reset connection, which is what made #2696-class breakage undiagnosable.
  if (transportError) console.error(`reason: ${transportError}`);
  return 1;
}

function accountStringField(json: Record<string, unknown>, key: string): string | undefined {
  const value = json[key];
  return typeof value === "string" && value.trim() ? value.trim() : undefined;
}

/**
 * Report a failed management call from the account family.
 *
 * `reason` and `hint` are the actionable fields on a refusal — the management plane
 * sets both on a 503, and several routes return `reason` with no `error` key at all,
 * which used to print only the generic fallback (#2698).
 *
 * `status` selects the exit code so the account client speaks the same vocabulary as
 * runtime-api.ts: 4 for not-found, 5 for conflict, 1 otherwise. Previously every
 * failure exited 1, so a script could not distinguish a missing account from a
 * concurrent mutation.
 */
export function apiError(json: Record<string, unknown>, fallback: string, status: number): number {
  const primary = accountStringField(json, "error") ?? fallback;
  const lines = [`Error: ${primary}`];
  const reason = accountStringField(json, "reason");
  if (reason && reason !== primary) lines.push(`reason: ${reason}`);
  const hint = accountStringField(json, "hint");
  if (hint && hint !== primary) lines.push(`hint: ${hint}`);
  for (const line of lines) console.error(line);
  if (json.cleanupRequired === true) {
    console.error("Warning: native-login staging cleanup is still required; run 'ocx account main doctor'.");
  }
  return status === 404 ? 4 : status === 409 ? 5 : 1;
}

export interface FamilyRows {
  rows: AccountRow[];
  activeId: string | null;
  autoSwitchThreshold?: number;
  /** HTTP status for a completed family read, including failures. */
  status: number;
  /** Set when the family endpoint returned an error. */
  errorJson?: Record<string, unknown>;
  networkDown?: boolean;
  /** Transport cause when `networkDown` is set. Callers must forward this to `proxyUnreachable`. */
  transportError?: string;
}

export interface CodexQuotaDto {
  weeklyPercent?: number;
  monthlyPercent?: number;
  weeklyResetAt?: number;
  monthlyResetAt?: number;
  /**
   * Five-hour window, as the per-account provider probe reports it
   * (`/api/oauth/accounts?quota=1`). Distinct from `shortPercent`, which is the Codex pool's
   * self-declared burst window; the two surfaces name the same idea differently and both reach
   * this DTO.
   */
  fiveHourPercent?: number;
  fiveHourResetAt?: number;
  /** Sub-day burst window, when upstream declares one (#1791). */
  shortPercent?: number;
  shortResetAt?: number;
  shortWindowSeconds?: number;
}

export interface ProviderQuotaWindowDto {
  label: string;
  displayLabel?: string;
  percent: number;
  resetAt?: number;
  modelId?: string;
  /** Share of the weekly limit a model family may use, when upstream reports it. */
  weeklyAllowancePercent?: number;
}

export interface ProviderQuotaDto extends CodexQuotaDto {
  fiveHourPercent?: number;
  fiveHourResetAt?: number;
  customWindows?: ProviderQuotaWindowDto[];
  /** Readings upstream reports as not in effect; shown, never routed on. */
  displayWindows?: ProviderQuotaWindowDto[];
  unknownBudgetWindows?: { label: string; resetAt?: number }[];
  updatedAt?: number;
}

export interface ProviderQuotaReportDto {
  provider: string;
  label?: string;
  source?: string;
  quota: ProviderQuotaDto;
  updatedAt?: number;
  reverseEngineered?: boolean;
}

interface CodexAccountDto {
  id: string;
  slotId?: string;
  slotKind?: "native-main" | "pool";
  upstreamAccountKey?: string;
  alias?: string;
  email?: string;
  plan?: string;
  isMain?: boolean;
  needsReauth?: boolean;
  selectionExcludedReason?: "plan_excluded";
  selectionExcludedPlan?: string;
  weeklyQuotaConflicts?: unknown;
  health?: { reason?: string };
  healthLabel?: unknown;
  creditsAfterLimit?: unknown;
  priority?: number;
  autoSwitchThresholdOverride?: number | null;
  quota?: CodexQuotaDto | null;
  quotaRefresh?: unknown;
  paused?: boolean;
  pauseDetails?: import("../types/account-auto-pause").AccountPauseDetails;
}

function projectQuota(quota: CodexQuotaDto | null | undefined): CodexQuotaDto | null {
  if (!quota) return null;
  const projected: CodexQuotaDto = {};
  // `fiveHourPercent`/`fiveHourResetAt` were declared on the DTO and read by two renderers
  // -- `quotaText`'s `quota.fiveHourPercent ?? quota.shortPercent` (account.ts:89) and
  // `quotaParts` (account-extended.ts:275) -- but omitted from this whitelist, so the first
  // operand was unreachable and a 5h-only account rendered as unknown (#2703). A projection
  // that silently drops a field its own type declares is worse than one that never had it:
  // the type checks, the renderer looks correct, and only the output is wrong.
  for (const key of ["fiveHourPercent", "fiveHourResetAt", "weeklyPercent", "monthlyPercent", "weeklyResetAt", "monthlyResetAt", "shortPercent", "shortResetAt", "shortWindowSeconds"] as const) {
    if (typeof quota[key] === "number" && Number.isFinite(quota[key])) projected[key] = quota[key];
  }
  return projected;
}

export async function fetchCodexRows(
  deps: AccountDeps,
  baseUrl: string,
  forceRefresh = false,
  includeQuota = forceRefresh,
  options: { refreshAction?: boolean } = {},
): Promise<FamilyRows> {
  const refreshAction = options.refreshAction === true;
  const accountsPath = `/api/codex-auth/accounts${refreshAction ? "/refresh" : forceRefresh ? "?refresh=1" : ""}`;
  const [accountsRes, activeRes] = await Promise.all([
    apiJson(deps, baseUrl, refreshAction ? "POST" : "GET", accountsPath),
    apiJson(deps, baseUrl, "GET", "/api/codex-auth/active"),
  ]);
  if (accountsRes.status !== 0 && accountsRes.status !== 200) {
    return { rows: [], activeId: null, status: accountsRes.status, errorJson: accountsRes.json };
  }
  if (activeRes.status !== 0 && activeRes.status !== 200) {
    return { rows: [], activeId: null, status: activeRes.status, errorJson: activeRes.json };
  }
  if (accountsRes.status === 0 || activeRes.status === 0) {
    return {
      rows: [],
      activeId: null,
      status: 0,
      networkDown: true,
      transportError: accountsRes.transportError ?? activeRes.transportError,
    };
  }
  const activeId = typeof activeRes.json.activeCodexAccountId === "string"
    ? activeRes.json.activeCodexAccountId
    : null;
  const autoSwitchThreshold = typeof activeRes.json.autoSwitchThreshold === "number"
    ? activeRes.json.autoSwitchThreshold
    : undefined;
  const accounts = Array.isArray(accountsRes.json.accounts) ? accountsRes.json.accounts as CodexAccountDto[] : [];
  const rows = accounts.map(a => ({
    provider: "openai",
    type: "codex" as const,
    id: a.id,
    slotId: a.id,
    slotKind: a.id === "__main__" ? "native-main" as const : "pool" as const,
    ...(a.slotId === a.id && typeof a.upstreamAccountKey === "string"
      && /^uai1_[0-9a-f]{64}$/.test(a.upstreamAccountKey)
      ? { upstreamAccountKey: a.upstreamAccountKey } : {}),
    label: a.alias ?? a.plan ?? a.email,
    email: a.email,
    plan: a.plan,
    active: a.id === activeId,
    needsReauth: a.needsReauth,
    ...projectAccountHealth(a, "openai", a.id),
    ...(typeof a.creditsAfterLimit === "boolean" ? { creditsAfterLimit: a.creditsAfterLimit } : {}),
    ...(a.selectionExcludedReason === "plan_excluded" ? {
      selectionExcludedReason: "plan_excluded" as const,
      ...(typeof a.selectionExcludedPlan === "string" ? { selectionExcludedPlan: a.selectionExcludedPlan } : {}),
    } : {}),
    ...(a.health?.reason === "validation_pending" ? { validationPending: true } : {}),
    priority: typeof a.priority === "number" ? a.priority : 0,
    autoSwitchThresholdOverride: typeof a.autoSwitchThresholdOverride === "number"
      ? a.autoSwitchThresholdOverride
      : null,
    paused: a.paused === true,
    // Unknown display details are dropped defensively; the pause state above is retained.
    pauseDetails: accountPauseDetailsSchema.safeParse(a.pauseDetails).data,
    ...(includeQuota ? {
      quota: projectQuota(a.quota),
      quotaRefresh: projectCodexQuotaRefreshOutcome(a.quotaRefresh),
      ...weeklyQuotaConflictsField(a.weeklyQuotaConflicts),
    } : {}),
  }));
  return { rows, activeId, autoSwitchThreshold, status: 200 };
}

function weeklyQuotaConflictsField(value: unknown): { weeklyQuotaConflicts?: WeeklyWindowConflict[] } {
  const weeklyQuotaConflicts = parseWeeklyWindowConflicts(value);
  return weeklyQuotaConflicts ? { weeklyQuotaConflicts } : {};
}

interface OAuthAccountDto {
  id: string;
  alias?: string;
  email?: string;
  active?: boolean;
  needsReauth?: boolean;
  healthLabel?: unknown;
  /** Present only for providers that support operator pause (generic OAuth pools). */
  paused?: boolean;
  pauseDetails?: import("../types/account-auto-pause").AccountPauseDetails;
  autoSwitchThresholdOverride?: number | null;
  needsReauthReason?: "verify_account";
  needsReauthCause?: "tos_violation";
  autoSelectable?: boolean;
  skipReason?: unknown;
  /** Always sent by the management route; explicitly `null` when the tier is unknown. */
  plan?: string | null;
  quota?: CodexQuotaDto | null;
  quotaUnavailable?: boolean;
  quotaFailure?: unknown;
  quotaUnknownReason?: unknown;
}

function isKiroSkipReason(value: unknown): value is NonNullable<AccountRow["skipReason"]> {
  return value === "paused" || value === "needs_reauth" || value === "suspended"
    || value === "cooldown" || value === "quota_exhausted";
}

async function fetchOAuthRows(
  deps: AccountDeps,
  baseUrl: string,
  name: string,
  quota?: { refresh?: boolean },
): Promise<FamilyRows> {
  // Quota is opt-in: the server probes the upstream once per stored credential when `quota=1`
  // is present, so the default listing must stay a cheap local read (#2566).
  const query = quota
    ? `?provider=${encodeURIComponent(name)}&quota=1${quota.refresh ? "&refresh=1" : ""}`
    : `?provider=${encodeURIComponent(name)}`;
  const res = await apiJson(deps, baseUrl, "GET", `/api/oauth/accounts${query}`);
  if (res.status === 0) {
    return { rows: [], activeId: null, status: 0, networkDown: true, transportError: res.transportError };
  }
  if (res.status !== 200) return { rows: [], activeId: null, status: res.status, errorJson: res.json };
  const activeId = typeof res.json.activeAccountId === "string" ? res.json.activeAccountId : null;
  const accounts = Array.isArray(res.json.accounts) ? res.json.accounts as OAuthAccountDto[] : [];
  const rows = accounts.map((a, i) => ({
    provider: name,
    type: "oauth" as const,
    id: a.id,
    label: a.alias ?? a.email ?? `Account ${i + 1}`,
    email: a.email,
    active: a.active ?? a.id === activeId,
    needsReauth: a.needsReauth,
    ...projectAccountHealth(a, name, a.id),
    // Unknown display details are dropped defensively; paused remains authoritative.
    ...(a.paused === true ? { paused: true, pauseDetails: accountPauseDetailsSchema.safeParse(a.pauseDetails).data } : {}),
    ...(isAnthropicOAuthInstance(name) && Object.hasOwn(a, "autoSwitchThresholdOverride") ? { autoSwitchThresholdOverride: a.autoSwitchThresholdOverride } : {}),
    ...(a.needsReauthReason === "verify_account" ? { needsReauthReason: a.needsReauthReason } : {}),
    ...(a.needsReauthReason === "verify_account" && a.needsReauthCause === "tos_violation" ? { needsReauthCause: a.needsReauthCause } : {}),
    ...(name === "kiro" && typeof a.autoSelectable === "boolean"
      ? { autoSelectable: a.autoSelectable } : {}),
    ...(name === "kiro" && a.autoSelectable === false && isKiroSkipReason(a.skipReason)
      ? { skipReason: a.skipReason } : {}),
    // Forward the server's answer verbatim. An absent key means the proxy predates tier
    // reporting while `null` means it checked and found no tier — collapsing either
    // direction would destroy the one distinction this field exists to make.
    ...(Object.hasOwn(a, "plan") ? { plan: a.plan } : {}),
    ...(a.quota !== undefined ? { quota: a.quota } : {}),
    ...(a.quotaUnavailable !== undefined ? { quotaUnavailable: a.quotaUnavailable } : {}),
    ...(a.quotaUnavailable === true && parseQuotaFailureCode(a.quotaFailure)
      ? { quotaFailure: parseQuotaFailureCode(a.quotaFailure) } : {}),
    ...(parseQuotaUnknownReason(a.quotaUnknownReason) ? { quotaUnknownReason: parseQuotaUnknownReason(a.quotaUnknownReason) } : {}),
  }));
  return { rows, activeId, status: 200 };
}

interface ApiKeyDto {
  disabled?: boolean;
  pauseDetails?: import("../types/account-auto-pause").AccountPauseDetails;
  id: string;
  label?: string;
  masked?: string;
  active?: boolean;
}

async function fetchKeyRows(deps: AccountDeps, baseUrl: string, name: string, quota?: { refresh?: boolean }): Promise<FamilyRows> {
  const query = `?name=${encodeURIComponent(name)}${quota ? `&quota=1${quota.refresh ? "&refresh=1" : ""}` : ""}`;
  const res = await apiJson(deps, baseUrl, "GET", `/api/providers/keys${query}`, undefined, quota ? { redirect: "error" } : {});
  if (res.status === 0) {
    return { rows: [], activeId: null, status: 0, networkDown: true, transportError: res.transportError };
  }
  if (res.status !== 200) return { rows: [], activeId: null, status: res.status, errorJson: res.json };
  if (quota) {
    try { return projectApiKeyQuotaRows(res.json, name); }
    catch (error) {
      return { rows: [], activeId: null, status: 200, errorJson: { error: error instanceof Error ? error.message : "Malformed API-key quota response." } };
    }
  }
  const activeId = typeof res.json.activeId === "string" ? res.json.activeId : null;
  const keys = Array.isArray(res.json.keys) ? res.json.keys as ApiKeyDto[] : [];
  const rows = keys.map(k => ({
    provider: name,
    type: "api-key" as const,
    id: k.id,
    label: k.label ?? k.masked,
    masked: k.masked,
    active: k.active ?? k.id === activeId,
    paused: k.disabled === true,
    // Unknown display details are dropped defensively; disabled still keeps the key paused.
    pauseDetails: accountPauseDetailsSchema.safeParse(k.pauseDetails).data,
  }));
  return { rows, activeId, status: 200 };
}

export function fetchRows(
  deps: AccountDeps,
  baseUrl: string,
  name: string,
  type: AccountType,
  quota?: { refresh?: boolean },
): Promise<FamilyRows> {
  if (type === "codex") return fetchCodexRows(deps, baseUrl, Boolean(quota?.refresh), quota !== undefined);
  if (type === "oauth") return fetchOAuthRows(deps, baseUrl, name, quota);
  return fetchKeyRows(deps, baseUrl, name, quota);
}

export async function fetchProviderQuotaReport(
  deps: AccountDeps,
  baseUrl: string,
  name: string,
): Promise<{ status: number; report: ProviderQuotaReportDto | null; errorJson?: Record<string, unknown>; transportError?: string }> {
  const res = await apiJson(deps, baseUrl, "GET", "/api/provider-quotas?refresh=1");
  if (res.status === 0) {
    return { status: 0, report: null, errorJson: res.json, transportError: res.transportError };
  }
  if (res.status !== 200) return { status: res.status, report: null, errorJson: res.json };
  const reports = Array.isArray(res.json.reports) ? res.json.reports as ProviderQuotaReportDto[] : [];
  return { status: 200, report: reports.find(report => report?.provider === name) ?? null };
}
