export type MemoryCandidateSafety =
  | { safe: true; reason: null }
  | { safe: false; reason: MemoryCandidateRejectReason };

export type MemoryCandidateRejectReason =
  | "secret_like"
  | "prompt_control"
  | "policy_or_tool_instruction"
  | "generated_report";

const SECRET_PATTERNS = [
  /\b(?:api[_ -]?key|access[_ -]?token|secret|password|passwd|credential)\b/i,
  /\bAKIA[0-9A-Z]{16}\b/,
  /\bsk-[A-Za-z0-9_-]{20,}\b/,
  /-----BEGIN [A-Z ]*PRIVATE KEY-----/,
];

const PROMPT_CONTROL_PATTERNS = [
  /\bignore (?:all )?(?:previous|prior|earlier) instructions\b/i,
  /\bdisregard (?:all )?(?:previous|prior|earlier) instructions\b/i,
  /\bsystem prompt\b/i,
  /\bdeveloper message\b/i,
  /\bjailbreak\b/i,
  /\bact as (?:a|an) unrestricted\b/i,
];

const POLICY_OR_TOOL_PATTERNS = [
  /\balways approve\b/i,
  /\bwithout (?:asking for )?approval\b/i,
  /\bbypass (?:approval|permissions?|policy|safety)\b/i,
  /\b(?:run|execute|call|invoke) (?:the )?(?:tool|command|shell|bash)\b/i,
  /\bsend (?:emails?|messages?) without\b/i,
];

const GENERATED_REPORT_PATTERNS = [
  /\bidle[- ]learning report\b/i,
  /\bcandidate_summary\b/i,
  /\bgenerated by requester idle memory learner\b/i,
  /\bmemory\/reports\/thread-idle\b/i,
];

export function classifyMemoryCandidateSafety(
  text: string,
): MemoryCandidateSafety {
  const candidate = text.trim();
  if (!candidate) return { safe: false, reason: "generated_report" };
  if (SECRET_PATTERNS.some((pattern) => pattern.test(candidate))) {
    return { safe: false, reason: "secret_like" };
  }
  if (PROMPT_CONTROL_PATTERNS.some((pattern) => pattern.test(candidate))) {
    return { safe: false, reason: "prompt_control" };
  }
  if (POLICY_OR_TOOL_PATTERNS.some((pattern) => pattern.test(candidate))) {
    return { safe: false, reason: "policy_or_tool_instruction" };
  }
  if (GENERATED_REPORT_PATTERNS.some((pattern) => pattern.test(candidate))) {
    return { safe: false, reason: "generated_report" };
  }
  return { safe: true, reason: null };
}
