const secretPatterns = [
  /\b(?:sk|ghp|github_pat|xoxb|xoxp|AKIA)[A-Za-z0-9_=-]{8,}\b/gu,
  /\b(?:token|secret|password|passwd|authorization|cookie|api[_-]?key)\s*[:=]\s*[^,\s]+/giu,
  /\bBearer\s+[A-Za-z0-9._~+/-]+=*\b/giu,
  /https?:\/\/[^/\s]+:[^@\s]+@[^/\s]+/giu,
] as const;

export interface RedactionResult {
  text: string;
  redactionsApplied: number;
}

export function redactText(value: string): RedactionResult {
  let redactionsApplied = 0;
  let text = value;
  for (const pattern of secretPatterns) {
    text = text.replace(pattern, () => {
      redactionsApplied += 1;
      return "<redacted>";
    });
  }
  return { text, redactionsApplied };
}

export function redactJsonValue(value: unknown): unknown {
  if (typeof value === "string") return redactText(value).text;
  if (Array.isArray(value)) return value.map((item) => redactJsonValue(item));
  if (typeof value !== "object" || value === null) return value;
  const record = value as Record<string, unknown>;
  const result: Record<string, unknown> = {};
  for (const [key, item] of Object.entries(record)) {
    result[key] = redactJsonValue(item);
  }
  return result;
}
