import { cappedAttempts, solutionText } from "./game.js";

export function buildStudySheet({
  modeLabel,
  runQuestions,
  state,
  results,
  score,
  createdAt
}) {
  const review = runQuestions
    .map((question) => ({
      id: question.id,
      chapterNumber:
        results.find((result) => result.id === question.chapterId)?.number ??
        "–",
      topic: question.topic,
      title: question.title,
      signal: question.signal,
      tool: question.tool,
      decision: question.decision,
      risk: question.risk,
      solution: solutionText(question),
      wrongAttempts: cappedAttempts(state.attempts?.[question.id]),
      hintUsed: (state.hints ?? []).includes(question.id)
    }))
    .filter((entry) => entry.wrongAttempts > 0 || entry.hintUsed);

  const totals = results.reduce(
    (summary, result) => ({
      clean: summary.clean + result.clean,
      mistakes: summary.mistakes + result.mistakes,
      hints: summary.hints + result.hints
    }),
    { clean: 0, mistakes: 0, hints: 0 }
  );

  return {
    modeLabel,
    createdAt,
    questionCount: runQuestions.length,
    xp: state.xp,
    integrity: state.integrity,
    score,
    review,
    results,
    totals
  };
}

export function renderStudySheetMarkdown(sheet) {
  const lines = [
    "# Kernel Panic — mein Lern-Spickzettel",
    "",
    `${sheet.modeLabel} · ${sheet.questionCount} Fragen · ${sheet.xp} XP · Integrität ${sheet.integrity} % · Score ${sheet.score}`,
    `Erstellt am ${sheet.createdAt}`,
    ""
  ];

  if (sheet.review.length > 0) {
    lines.push(
      `## Diese Fragen saßen nicht sofort (${sheet.review.length})`,
      ""
    );
    for (const entry of sheet.review) {
      lines.push(
        `### Kapitel ${entry.chapterNumber} · ${entry.topic} · „${entry.title}"`,
        "",
        `- **Lösung:** \`${entry.solution}\``,
        `- **Signal:** ${entry.signal}`,
        `- **Werkzeug:** \`${entry.tool}\``,
        `- **Entscheidung:** ${entry.decision}`,
        `- **Risiko:** ${entry.risk}`,
        `- **Fehlversuche:** ${entry.wrongAttempts}${entry.hintUsed ? " · Hinweis genutzt" : ""}`,
        ""
      );
    }
  } else {
    lines.push(
      "## Nacharbeit",
      "",
      "Keine Frage brauchte einen zweiten Versuch oder einen Hinweis.",
      ""
    );
  }

  lines.push(
    "## Kapitelbilanz",
    "",
    `${sheet.totals.clean} ohne Hilfe gelöst · ${sheet.totals.mistakes} Fehler · ${sheet.totals.hints} Hinweise`,
    ""
  );
  for (const result of sheet.results) {
    lines.push(
      `- Kapitel ${result.number} · ${result.topic}: ${result.clean}/${result.total} ohne Hilfe, ${result.mistakes} Fehler, ${result.hints} Hinweise`
    );
  }
  lines.push("");

  return lines.join("\n");
}

// RUN_MODES kennt nur „Kurslauf" und „Lernmodus", beide umlautfrei.
export function studySheetFileName(sheet) {
  const mode = sheet.modeLabel.toLowerCase().replace(/[^a-z0-9]+/g, "-");
  return `kernel-panic-spickzettel-${mode}-${sheet.createdAt}.md`;
}
