export type ImportMode = 'overwrite' | 'incremental';

export type ImportQuestion = {
  content: string;
  type: 'single' | 'multiple' | 'judgment' | 'text';
  category?: string;
  options?: string[];
  answer: string | string[];
  analysis: string;
  score: number;
};

export type ParseResult = {
  questions: ImportQuestion[];
  errors: string[];
};

const normalizeType = (raw: string): ImportQuestion['type'] | null => {
  const t = String(raw || '').trim();
  if (!t) return null;
  const map: Record<string, ImportQuestion['type']> = {
    单选: 'single',
    单选题: 'single',
    single: 'single',
    多选: 'multiple',
    多选题: 'multiple',
    multiple: 'multiple',
    判断: 'judgment',
    判断题: 'judgment',
    judgment: 'judgment',
    文本: 'text',
    文字: 'text',
    文字题: 'text',
    文字描述: 'text',
    文字描述题: 'text',
    简答: 'text',
    问答: 'text',
    text: 'text',
  };
  return map[t] ?? null;
};

const splitMulti = (raw: string) =>
  String(raw || '')
    .split(/[|,，、\s]+/g)
    .map((s) => s.trim())
    .filter(Boolean);

const normalizeJudgmentAnswer = (raw: string) => {
  const v = String(raw || '').trim();
  if (!v) return '';
  const yes = new Set(['正确', '对', '是', 'true', 'True', 'TRUE', '1', 'Y', 'y', 'yes', 'YES']);
  const no = new Set(['错误', '错', '否', '不是', 'false', 'False', 'FALSE', '0', 'N', 'n', 'no', 'NO']);
  if (yes.has(v)) return '正确';
  if (no.has(v)) return '错误';
  return v;
};

const parseLine = (line: string) => {
  const trimmed = line.trim();
  if (!trimmed) return null;
  if (trimmed.startsWith('#')) return null;
  if (trimmed.startsWith('题型')) return null;

  const hasPipeDelimiter = trimmed.includes('|');
  const hasCsvDelimiter = /\t|,|，/g.test(trimmed);

  const parts = hasPipeDelimiter
    ? trimmed.split('|').map((p) => p.trim())
    : hasCsvDelimiter
      ? trimmed.split(/\t|,|，/g).map((p) => p.trim())
      : [];

  if (parts.length < 4) return { error: `字段不足：${trimmed}` };

  const type = normalizeType(parts[0]);
  if (!type) return { error: `题型无法识别：${trimmed}` };

  const category = parts[1] || '通用';
  const score = Number(parts[2]);
  if (!Number.isFinite(score) || score < 0) return { error: `分值必须是非负数：${trimmed}` };
  const allowEmptyAnswer = score === 0;

  const content = parts[3];
  if (!content) return { error: `题目内容不能为空：${trimmed}` };

  const pickDelimitedFields = () => {
    if (!hasPipeDelimiter && hasCsvDelimiter) {
      return {
        optionsRaw: parts[4] ?? '',
        answerRaw: parts[5] ?? '',
        analysisRaw: parts[6] ?? '',
        optionsTokens: [] as string[],
      };
    }

    if (!hasPipeDelimiter) {
      return { optionsRaw: '', answerRaw: '', analysisRaw: '', optionsTokens: [] as string[] };
    }

    if (parts.length === 5) {
      return { optionsRaw: '', answerRaw: parts[4] ?? '', analysisRaw: '', optionsTokens: [] as string[] };
    }

    const analysisRaw = parts[parts.length - 1] ?? '';
    const answerRaw = parts[parts.length - 2] ?? '';
    const optionsTokens = parts.slice(4, Math.max(4, parts.length - 2));
    return { optionsRaw: optionsTokens.join('|'), answerRaw, analysisRaw, optionsTokens };
  };

  const { optionsRaw, answerRaw, analysisRaw, optionsTokens } = pickDelimitedFields();

  const question: ImportQuestion = { type, category, score, content, answer: '', analysis: String(analysisRaw || '').trim().slice(0, 255) };

  if (type === 'single' || type === 'multiple') {
    // 如果使用 | 分隔（推荐格式），选项必须严格按 | 切分；选项文本内允许出现逗号/顿号等标点
    // 否则（CSV/Tab 分隔）才对 optionsRaw 做更宽松的 split
    const options = hasPipeDelimiter ? optionsTokens.map((s) => s.trim()).filter(Boolean) : splitMulti(optionsRaw);
    if (options.length < 2) return { error: `选项至少2个：${trimmed}` };
    const answerTokens = splitMulti(answerRaw);
    if (answerTokens.length === 0) {
      if (allowEmptyAnswer) {
        question.options = options;
        question.answer = type === 'multiple' ? [] : '';
        return { question };
      }
      return { error: `答案不能为空：${trimmed}` };
    }
    const toValue = (token: string) => {
      const m = token.trim().match(/^([A-Za-z])$/);
      if (!m) return token;
      const idx = m[1].toUpperCase().charCodeAt(0) - 65;
      return options[idx] ?? token;
    };
    question.options = options;
    const normalized = answerTokens.map(toValue).filter(Boolean);
    question.answer = type === 'multiple' ? normalized : normalized[0];
    return { question };
  }

  if (type === 'judgment') {
    const a = normalizeJudgmentAnswer(answerRaw);
    if (!a) {
      if (allowEmptyAnswer) {
        question.answer = '';
        return { question };
      }
      return { error: `答案不能为空：${trimmed}` };
    }
    question.answer = a;
    return { question };
  }

  const textAnswer = String(answerRaw || '').trim();
  if (!textAnswer) {
    if (allowEmptyAnswer) {
      question.answer = '';
      return { question };
    }
    return { error: `答案不能为空：${trimmed}` };
  }
  question.answer = textAnswer;
  return { question };
};

export const parseTextQuestions = (text: string): ParseResult => {
  const lines = String(text || '')
    .split(/\r?\n/g)
    .map((l) => l.trim())
    .filter((l) => l.length > 0);

  const errors: string[] = [];
  const list: ImportQuestion[] = [];

  for (let i = 0; i < lines.length; i++) {
    const raw = lines[i];
    const parsed = parseLine(raw);
    if (!parsed) continue;
    if ('error' in parsed) {
      errors.push(`第${i + 1}行：${parsed.error}`);
      continue;
    }
    if (parsed.question) list.push(parsed.question);
  }

  const dedup = new Map<string, ImportQuestion>();
  for (const q of list) {
    const key = q.content.trim();
    if (!key) continue;
    dedup.set(key, q);
  }

  return { questions: Array.from(dedup.values()), errors };
};
