/** Public API-key quota projection; private probe identity stays on the server. */
import { parseQuotaFailureCode, parseQuotaUnknownReason, type AccountQuotaFields, type ProviderQuota, type ProviderQuotaWindow, type ProviderQuotaCreditsUsd, type QuotaUnknownReason } from "../providers/quota-types";
import { terminalSafeText } from "./runtime-api";
import type { AccountRow, FamilyRows } from "./account-api";
import { accountPauseDetailsSchema } from "../config/schema/account-auto-pause";

function record(value: unknown): Record<string, unknown> {
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Malformed API-key quota response.");
  return value as Record<string, unknown>;
}
function finite(value: unknown): number {
  if (typeof value !== "number" || !Number.isFinite(value)) throw new Error("Malformed API-key quota response.");
  return value;
}
function optionalString(row: Record<string, unknown>, key: string): string | undefined {
  if (row[key] === undefined) return undefined;
  if (typeof row[key] !== "string") throw new Error("Malformed API-key quota response.");
  return row[key];
}
function optionalBoolean(row: Record<string, unknown>, key: string): boolean | undefined {
  if (row[key] === undefined) return undefined;
  if (typeof row[key] !== "boolean") throw new Error("Malformed API-key quota response.");
  return row[key];
}
function windowProjection(value: unknown): ProviderQuotaWindow {
  const row = record(value);
  const label = optionalString(row, "label");
  if (label === undefined) throw new Error("Malformed API-key quota response.");
  const result: ProviderQuotaWindow = { label, percent: finite(row.percent) };
  const displayLabel = optionalString(row, "displayLabel");
  if (displayLabel !== undefined) result.displayLabel = displayLabel;
  if (row.resetAt !== undefined) result.resetAt = finite(row.resetAt);
  if (row.passiveObservedAt !== undefined) result.passiveObservedAt = finite(row.passiveObservedAt);
  if (row.scope !== undefined) {
    if (row.scope !== "model") throw new Error("Malformed API-key quota response.");
    result.scope = row.scope;
  }
  if (row.rejected !== undefined) {
    if (row.rejected !== true) throw new Error("Malformed API-key quota response.");
    result.rejected = true;
  }
  return result;
}
function creditsProjection(value: unknown): ProviderQuotaCreditsUsd {
  const row = record(value);
  const result: ProviderQuotaCreditsUsd = {
    used: finite(row.used), limit: finite(row.limit), remaining: finite(row.remaining), percent: finite(row.percent),
  };
  if (row.expiresAt !== undefined) result.expiresAt = finite(row.expiresAt);
  const unlimited = optionalBoolean(row, "unlimited");
  if (unlimited !== undefined) result.unlimited = unlimited;
  return result;
}
function quotaProjection(value: unknown): ProviderQuota | null {
  if (value === null) return null;
  const row = record(value);
  const result: ProviderQuota = { updatedAt: finite(row.updatedAt) };
  for (const key of ["fiveHourPercent", "fiveHourResetAt", "weeklyPercent", "weeklyResetAt", "monthlyPercent", "monthlyResetAt", "kiroCreditsUsed", "kiroCreditsLimit"] as const) {
    if (row[key] !== undefined) result[key] = finite(row[key]);
  }
  if (row.customWindows !== undefined) {
    if (!Array.isArray(row.customWindows)) throw new Error("Malformed API-key quota response.");
    result.customWindows = row.customWindows.map(windowProjection);
  }
  if (row.unknownBudgetWindows !== undefined) {
    if (!Array.isArray(row.unknownBudgetWindows)) throw new Error("Malformed API-key quota response.");
    result.unknownBudgetWindows = row.unknownBudgetWindows.map(value => {
      const item = record(value);
      const label = optionalString(item, "label");
      if (label === undefined) throw new Error("Malformed API-key quota response.");
      return { label, ...(item.resetAt === undefined ? {} : { resetAt: finite(item.resetAt) }) };
    });
  }
  if (row.creditsUsd !== undefined) result.creditsUsd = creditsProjection(row.creditsUsd);
  return result;
}

/** Only opt-in reads use the strict DTO boundary; legacy cheap lists retain their contract. */
export function projectApiKeyQuotaRows(value: unknown, provider: string): FamilyRows {
  const body = record(value);
  if (!Array.isArray(body.keys) || (body.activeId !== null && typeof body.activeId !== "string")) {
    throw new Error("Malformed API-key quota response.");
  }
  const activeId = body.activeId;
  const rows: AccountRow[] = body.keys.map(value => {
    const row = record(value);
    const id = optionalString(row, "id");
    if (!id) throw new Error("Malformed API-key quota response.");
    const quotaMode = row.quotaMode;
    if (quotaMode === undefined) throw new Error("API-key quota is unverified: server did not report quotaMode. Update the proxy and retry.");
    if (quotaMode !== "probe" && quotaMode !== "passive" && quotaMode !== "unsupported") throw new Error("Malformed API-key quota response.");
    const fields: AccountQuotaFields = { quotaMode };
    if (row.quota !== undefined) fields.quota = quotaProjection(row.quota);
    const unavailable = optionalBoolean(row, "quotaUnavailable");
    if (unavailable !== undefined) fields.quotaUnavailable = unavailable;
    if (row.quotaFailure !== undefined) {
      const failure = parseQuotaFailureCode(row.quotaFailure);
      if (!failure) throw new Error("Malformed API-key quota response.");
      if (unavailable === true) fields.quotaFailure = failure;
    }
    // #8397: a reason a newer proxy adds is dropped, not fatal; a non-string is malformed.
    const unknownReason = parseQuotaUnknownReason(optionalString(row, "quotaUnknownReason"));
    if (unknownReason) fields.quotaUnknownReason = unknownReason;
    // Display-only: a malformed read time is dropped like an unknown reason, not fatal to the listing.
    if (typeof row.quotaReadAt === "number" && Number.isFinite(row.quotaReadAt) && row.quotaReadAt >= 0) fields.quotaReadAt = row.quotaReadAt;
    const masked = optionalString(row, "masked");
    return { provider, type: "api-key", id, label: optionalString(row, "label") ?? masked,
      masked, active: optionalBoolean(row, "active") ?? id === activeId,
      // Same projection as the plain key listing: disabled keeps the key paused, unknown details drop.
      paused: row.disabled === true, pauseDetails: accountPauseDetailsSchema.safeParse(row.pauseDetails).data, ...fields };
  });
  return { rows, activeId, status: 200 };
}

const UNKNOWN_REASON_TEXT: Record<QuotaUnknownReason, string> = {
  no_balance_source: "no balance source",
  passive_not_observed: "not observed yet",
  read_failed: "read failed",
  not_read: "not read",
  not_reported: "provider reported none",
};
export function quotaUnknownReasonText(reason: QuotaUnknownReason): string {
  return UNKNOWN_REASON_TEXT[reason];
}

/** "read 3 min ago"; a clock skewed into the future reads as just now. */
function readAgeText(readAt: number | undefined, now = Date.now()): string {
  if (readAt === undefined) return "";
  const minutes = Math.floor(Math.max(0, now - readAt) / 60_000);
  if (minutes < 1) return "; read just now";
  if (minutes < 60) return `; read ${minutes} min ago`;
  const hours = Math.floor(minutes / 60);
  return hours < 48 ? `; read ${hours} h ago` : `; read ${Math.floor(hours / 24)} d ago`;
}

export function apiKeyQuotaText(row: AccountRow): string {
  const mode = row.quotaMode;
  if (!mode) return "unverified";
  // Without a reader there is no balance source, whichever proxy version answered.
  if (mode === "unsupported") return `unsupported: balance UNKNOWN (${quotaUnknownReasonText("no_balance_source")})`;
  const read = readAgeText(row.quotaReadAt);
  const unknown = row.quotaUnknownReason ? `; balance UNKNOWN (${quotaUnknownReasonText(row.quotaUnknownReason)})` : "";
  if (row.quotaUnavailable) return `${mode}: unavailable${row.quotaFailure ? ` (${row.quotaFailure})` : ""}${unknown}${read}`;
  const quota = row.quota;
  if (!quota) return unknown ? `${mode}: ${unknown.slice(2)}${read}` : `${mode}: not measured${read}`;
  const parts: string[] = [];
  for (const [label, percent] of [["5h", quota.fiveHourPercent], ["wk", quota.weeklyPercent], ["mo", quota.monthlyPercent]] as const) {
    if (percent !== undefined) parts.push(`${label} ${percent}%`);
  }
  for (const window of quota.customWindows ?? []) {
    // Labels are upstream text: keep terminal controls out of the human table.
    const label = terminalSafeText(window.displayLabel ?? window.label);
    // Only a probe that supplied its own display text adds the reset clock; every other
    // provider keeps the dev-era text byte for byte.
    const resetAt = window.displayLabel === undefined || window.resetAt === undefined ? undefined : new Date(window.resetAt);
    const reset = resetAt && Number.isFinite(resetAt.getTime()) ? `; resets ${resetAt.toISOString()}` : "";
    parts.push(`${label} ${window.percent}%${window.rejected ? " (rejected)" : ""}${reset}`);
  }
  for (const window of quota.unknownBudgetWindows ?? []) {
    const resetAt = window.resetAt === undefined ? undefined : new Date(window.resetAt);
    const reset = resetAt && Number.isFinite(resetAt.getTime()) ? `; resets ${resetAt.toISOString()}` : "";
    parts.push(`${terminalSafeText(window.label)} unknown${reset}`);
  }
  if (quota.creditsUsd) {
    const c = quota.creditsUsd;
    parts.push(`USD ${c.used}/${c.unlimited ? "unlimited" : c.limit} used; ${c.remaining} remaining (${c.percent}%)`);
  }
  if (quota.kiroCreditsUsed !== undefined || quota.kiroCreditsLimit !== undefined) parts.push(`credits ${quota.kiroCreditsUsed ?? "?"}/${quota.kiroCreditsLimit ?? "?"}`);
  return `${mode}: ${parts.join("; ") || "not measured"}${read}`;
}
