const ghAuthStatusLinePatterns = [
  /^\s*(?:[\u2713\u2714]\s*)?Logged in to\s+\S+\s+account\s+\S+\s+\([^)]+\)\s*$/iu,
  /^\s*(?:[\u2713\u2714]\s*)?Token:\s+\S+\s*$/iu,
  /^\s*(?:[\u2713\u2714]\s*)?Token scopes?:\s+.*$/iu,
  /^\s*(?:-\s*)?Token(?:\s+(?:scopes?|source|preview|value))?\s*[:=]\s*\S+.*$/iu,
] as const;

const tokenLikePatterns = [
  /\bgh[pousr]_[A-Za-z0-9_]{6,}\b/gu,
  /\bgithub_pat_[A-Za-z0-9_]{6,}\b/gu,
  /\b(?:sk|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 const ghAuthStatusWrapperHint = "Use bun scripts/cli.ts gh auth status --repo pikasTech/unidesk for structured redacted GitHub auth diagnostics.";

export function sanitizeTaskOutputText(text: string): string {
  let redactionsApplied = 0;
  let ghAuthStatusRedactions = 0;
  const lines = String(text || "").split(/\r?\n/u).map((line) => {
    if (ghAuthStatusLinePatterns.some((pattern) => pattern.test(line))) {
      redactionsApplied += 1;
      ghAuthStatusRedactions += 1;
      return "[redacted gh auth status line]";
    }
    let next = line;
    for (const pattern of tokenLikePatterns) {
      next = next.replace(pattern, () => {
        redactionsApplied += 1;
        return "<redacted>";
      });
    }
    return next;
  });
  const sanitized = lines.join("\n");
  if (redactionsApplied === 0 || ghAuthStatusRedactions === 0 || sanitized.includes(ghAuthStatusWrapperHint)) return sanitized;
  return `${sanitized}\n${ghAuthStatusWrapperHint}`;
}
