// 文本腐蚀（PRD §6.5）：原文案保持干净，运行时按阶段在渲染层替换。
import { director } from "./director";

// 同音错字对照表（全 10 组，逐字实现）
export const TYPOS: [string, string][] = [
  ["幸福", "辛福"], ["开心", "开欣"], ["美好", "美妤"], ["大家", "大伽"],
  ["微笑", "微效"], ["明天", "名天"], ["甜", "恬"], ["阳光", "央光"],
  ["朋友", "棚友"], ["永远", "泳远"],
];

let sentenceCount = 0;

function applyOneTypo(text: string): string {
  for (const [good, bad] of TYPOS) {
    const i = text.indexOf(good);
    if (i >= 0) return text.slice(0, i) + bad + text.slice(i + good.length);
  }
  return text;
}

function dupPunct(text: string): string {
  return text.replace(/([。！？!?])(?=[^。！？!?]|$)/, "$1$1");
}

function triplePunct(text: string): string {
  const m = text.match(/[。！？!?…]$/);
  if (m) return text + m[0] + m[0];
  return text + "。。";
}

// speaker: NPC id；咪咪是文本腐蚀主要载体（优先命中）
export function corruptText(text: string, speaker: string): string {
  const stage = director.stage;
  if (stage < 2) return text;
  sentenceCount++;
  const mimi = speaker === "mimi";
  let out = text;
  if (stage === 2) {
    // 偶发标点重复（每 80 句 1 次；咪咪优先 → 每 16 句）
    if (sentenceCount % (mimi ? 16 : 80) === 0) out = dupPunct(out);
  } else if (stage === 3) {
    // 每 50 句 1 个同音错字（咪咪 → 每 10 句）
    if (sentenceCount % (mimi ? 10 : 50) === 0) out = applyOneTypo(out);
    if (sentenceCount % (mimi ? 16 : 80) === 0) out = dupPunct(out);
  } else if (stage >= 4) {
    // 错字加密（咪咪每 2 句，其他每 8 句）+ 咪咪句尾标点 ×3
    if (sentenceCount % (mimi ? 2 : 8) === 0) out = applyOneTypo(applyOneTypo(out));
    if (mimi) out = triplePunct(out);
  }
  return out;
}
