import { resolveText } from '../i18n/types';
import type { Locale } from '../i18n/types';
import { docStrings, formatDocDate } from './docStrings';
import { QUIZ_PASS_PCT, QUIZ_QUESTIONS } from './quizContent';
import type { CompanyProfile, ContentPack } from './types';

/** Aufgelöste Quizfrage in einer Zielsprache. */
export interface QuizQuestion {
  readonly id: string;
  readonly question: string;
  readonly options: readonly [string, string, string];
  readonly correctIndex: 0 | 1 | 2;
  readonly explanation: string;
}

/** Testergebnis einer Person. */
export interface QuizScore {
  readonly correct: number;
  readonly total: number;
  readonly pct: number;
  readonly passed: boolean;
}

/** Eintrag im lokalen Schulungsregister (Art.-4-Nachweis). */
export interface TrainingRecord {
  readonly id: string;
  readonly name: string;
  readonly date: string;
  readonly scorePct: number;
  readonly passed: boolean;
}

/** Liefert den Fragenkatalog in der gewünschten Sprache. */
export function getQuiz(locale: Locale): readonly QuizQuestion[] {
  return QUIZ_QUESTIONS.map((q) => ({
    id: q.id,
    question: resolveText(q.question, locale),
    options: [
      resolveText(q.options[0], locale),
      resolveText(q.options[1], locale),
      resolveText(q.options[2], locale),
    ],
    correctIndex: q.correctIndex,
    explanation: resolveText(q.explanation, locale),
  }));
}

/**
 * Wertet abgegebene Antworten aus.
 *
 * @param answers - Gewählter Optionsindex je Frage (Reihenfolge des Katalogs)
 */
export function scoreQuiz(answers: readonly (number | null)[]): QuizScore {
  const total = QUIZ_QUESTIONS.length;
  const correct = QUIZ_QUESTIONS.reduce(
    (acc, q, i) => acc + (answers[i] === q.correctIndex ? 1 : 0),
    0,
  );
  const pct = Math.round((correct / total) * 100);
  return { correct, total, pct, passed: pct >= QUIZ_PASS_PCT };
}

interface CertStrings {
  readonly title: string;
  readonly intro: string;
  readonly name: string;
  readonly date: string;
  readonly result: string;
  readonly resultPassed: string;
  readonly resultFailed: string;
  readonly topics: string;
  readonly topicList: string;
  readonly evidence: string;
  readonly signature: string;
  readonly logTitle: string;
  readonly logIntro: string;
  readonly logCols: string;
}

const CERT: Readonly<Record<'de' | 'en', CertStrings>> = {
  de: {
    title: 'Nachweis KI-Kompetenz (Art. 4 EU-KI-VO)',
    intro:
      'Die nachfolgend genannte Person hat den KI-Kompetenztest des Unternehmens absolviert. Der Test vermittelt und prüft die Grundlagen für den verantwortungsvollen Umgang mit KI-Systemen.',
    name: 'Name',
    date: 'Datum',
    result: 'Ergebnis',
    resultPassed: 'BESTANDEN',
    resultFailed: 'NICHT BESTANDEN — Wiederholung erforderlich',
    topics: 'Geprüfte Themen',
    topicList:
      'Funktionsweise und Grenzen von KI · Umgang mit vertraulichen Daten · Prüfung von KI-Ausgaben (Halluzinationen) · menschliche Aufsicht · Transparenzpflichten (Art. 50) · verbotene Praktiken (Art. 5) · Hochrisiko-KI (Annex III) · DSGVO · interne Meldewege (Art. 73) · Freigabeprozess (Schatten-KI) · Kennzeichnung KI-generierter Inhalte · KI-Kompetenzpflicht (Art. 4)',
    evidence:
      'Dieser Nachweis ist Teil der Art.-4-Dokumentation des Unternehmens (Schulungsplan & Nachweis KI-Kompetenz) und wird dort abgelegt.',
    signature: 'Ort, Datum: _______________  Unterschrift Beschäftigte/r: _______________  Unterschrift Arbeitgeber: _______________',
    logTitle: 'Schulungsregister KI-Kompetenz (Art. 4 EU-KI-VO)',
    logIntro: 'Fortlaufender Nachweis der durchgeführten KI-Kompetenztests. Bestehensgrenze: {pct} %.',
    logCols: '| Datum | Name | Ergebnis | Status |',
  },
  en: {
    title: 'Evidence of AI literacy (Art. 4 EU AI Act)',
    intro:
      'The person named below has completed the company’s AI literacy test. The test teaches and verifies the basics of responsible use of AI systems.',
    name: 'Name',
    date: 'Date',
    result: 'Result',
    resultPassed: 'PASSED',
    resultFailed: 'NOT PASSED — retake required',
    topics: 'Topics covered',
    topicList:
      'How AI works and its limits · handling confidential data · checking AI output (hallucinations) · human oversight · transparency obligations (Art. 50) · prohibited practices (Art. 5) · high-risk AI (Annex III) · GDPR · internal reporting channels (Art. 73) · approval process (shadow AI) · marking AI-generated content · AI literacy duty (Art. 4)',
    evidence:
      'This evidence forms part of the company’s Art. 4 documentation (AI literacy training plan & record) and is filed there.',
    signature: 'Place, date: _______________  Signature employee: _______________  Signature employer: _______________',
    logTitle: 'AI literacy training register (Art. 4 EU AI Act)',
    logIntro: 'Continuous record of completed AI literacy tests. Pass threshold: {pct} %.',
    logCols: '| Date | Name | Score | Status |',
  },
};

function certStrings(locale: Locale): CertStrings {
  return locale === 'de' ? CERT.de : CERT.en;
}

/**
 * Erzeugt das druckbare Zertifikat (Art.-4-Nachweis) als Markdown.
 *
 * @param name - Name der geprüften Person
 * @param score - Testergebnis
 * @param pack - Content-Pack (Versionsangabe)
 * @param today - Datum im ISO-Format
 * @param profile - Firmenprofil (Briefkopf)
 * @param locale - Dokumentsprache
 */
export function certificateDoc(
  name: string,
  score: QuizScore,
  pack: ContentPack,
  today: string,
  profile?: CompanyProfile,
  locale: Locale = 'de',
): string {
  const s = docStrings(locale);
  const c = certStrings(locale);
  const company = profile && profile.name.trim() !== '' ? profile.name : '_______________';
  return [
    `# ${c.title}`,
    '',
    `**${s.meta.company}:** ${company} · Content-Pack v${pack.version}`,
    '',
    s.disclaimer,
    '',
    c.intro,
    '',
    `| | |`,
    `|---|---|`,
    `| **${c.name}** | ${name} |`,
    `| **${c.date}** | ${formatDocDate(today, locale)} |`,
    `| **${c.result}** | ${score.correct}/${score.total} (${score.pct} %) — **${score.passed ? c.resultPassed : c.resultFailed}** |`,
    '',
    `## ${c.topics}`,
    '',
    c.topicList,
    '',
    c.evidence,
    '',
    c.signature,
  ].join('\n');
}

interface PrintStrings {
  readonly testTitle: string;
  readonly testIntro: string;
  readonly nameDateLine: string;
  readonly testFooter: string;
  readonly keyTitle: string;
  readonly keyIntro: string;
  readonly keyCorrect: string;
  readonly keyWhy: string;
  readonly handoutTitle: string;
  readonly handoutIntro: string;
  readonly handoutFooter: string;
}

const PRINT: Readonly<Record<'de' | 'en', PrintStrings>> = {
  de: {
    testTitle: 'KI-Kompetenztest (Art. 4 EU-KI-VO) — Papierfassung',
    testIntro:
      'Bitte kreuzen Sie je Frage genau eine Antwort an. Bestehensgrenze: {pct} % ({min} von {total} Fragen). Die Auswertung erfolgt mit dem Lösungsbogen; das Ergebnis wird im Schulungsregister dokumentiert.',
    nameDateLine: '**Name:** ______________________________  **Datum:** ______________  **Abteilung:** ______________________________',
    testFooter: 'Unterschrift Beschäftigte/r: _______________  Ausgewertet durch (Name, Unterschrift): _______________  Ergebnis: ______ / {total}',
    keyTitle: 'KI-Kompetenztest — Lösungsbogen (nur für Auswertende)',
    keyIntro: 'Alle Fragen mit richtiger Antwort und Erklärung. Bestehensgrenze: {pct} % ({min} von {total} Fragen).',
    keyCorrect: 'Richtige Antwort',
    keyWhy: 'Erklärung',
    handoutTitle: 'Schulungshandout: Die 12 wichtigsten Regeln im Umgang mit KI',
    handoutIntro:
      'Dieses Handout fasst die Kernregeln für den Arbeitsalltag zusammen und dient als Schulungsunterlage nach Art. 4 EU-KI-VO. Es kann vor dem Kompetenztest ausgeteilt werden.',
    handoutFooter:
      'Bei Fragen oder Vorfällen: an die/den KI-Beauftragte/n wenden (siehe interne Melde- und Eskalationsrichtlinie).',
  },
  en: {
    testTitle: 'AI literacy test (Art. 4 EU AI Act) — paper version',
    testIntro:
      'Please tick exactly one answer per question. Pass threshold: {pct} % ({min} of {total} questions). Marking is done with the answer key; the result is documented in the training register.',
    nameDateLine: '**Name:** ______________________________  **Date:** ______________  **Department:** ______________________________',
    testFooter: 'Signature employee: _______________  Marked by (name, signature): _______________  Score: ______ / {total}',
    keyTitle: 'AI literacy test — answer key (for markers only)',
    keyIntro: 'All questions with the correct answer and explanation. Pass threshold: {pct} % ({min} of {total} questions).',
    keyCorrect: 'Correct answer',
    keyWhy: 'Explanation',
    handoutTitle: 'Training handout: the 12 most important rules for working with AI',
    handoutIntro:
      'This handout summarises the core rules for everyday work and serves as training material under Art. 4 EU AI Act. It can be handed out before the literacy test.',
    handoutFooter:
      'For questions or incidents: contact the AI officer (see the internal reporting and escalation policy).',
  },
};

function printStrings(locale: Locale): PrintStrings {
  return locale === 'de' ? PRINT.de : PRINT.en;
}

const OPTION_LETTERS = ['A', 'B', 'C'] as const;

function minCorrect(): number {
  return Math.ceil((QUIZ_PASS_PCT / 100) * QUIZ_QUESTIONS.length);
}

function fillIn(template: string): string {
  return template
    .replace('{pct}', String(QUIZ_PASS_PCT))
    .replace('{min}', String(minCorrect()))
    .replaceAll('{total}', String(QUIZ_QUESTIONS.length));
}

/**
 * Erzeugt die Papierfassung des Kompetenztests (zum Ausdrucken und
 * handschriftlichen Ausfüllen) als Markdown.
 */
export function printableTestDoc(
  pack: ContentPack,
  today: string,
  profile?: CompanyProfile,
  locale: Locale = 'de',
): string {
  const s = docStrings(locale);
  const p = printStrings(locale);
  const company = profile && profile.name.trim() !== '' ? profile.name : '_______________';
  const lines = [
    `# ${p.testTitle}`,
    '',
    `**${s.meta.company}:** ${company} · ${s.inventory.asOf}: ${formatDocDate(today, locale)} · Content-Pack v${pack.version}`,
    '',
    p.nameDateLine,
    '',
    fillIn(p.testIntro),
    '',
  ];
  getQuiz(locale).forEach((q, i) => {
    lines.push(`## ${i + 1}. ${q.question}`, '');
    q.options.forEach((option, oi) => {
      lines.push(`- ☐ **${OPTION_LETTERS[oi]})** ${option}`);
    });
    lines.push('');
  });
  lines.push(fillIn(p.testFooter));
  return lines.join('\n');
}

/** Erzeugt den Lösungsbogen (richtige Antworten + Erklärungen) als Markdown. */
export function answerKeyDoc(
  pack: ContentPack,
  today: string,
  profile?: CompanyProfile,
  locale: Locale = 'de',
): string {
  const s = docStrings(locale);
  const p = printStrings(locale);
  const company = profile && profile.name.trim() !== '' ? profile.name : '_______________';
  const lines = [
    `# ${p.keyTitle}`,
    '',
    `**${s.meta.company}:** ${company} · ${s.inventory.asOf}: ${formatDocDate(today, locale)} · Content-Pack v${pack.version}`,
    '',
    fillIn(p.keyIntro),
    '',
  ];
  getQuiz(locale).forEach((q, i) => {
    lines.push(
      `## ${i + 1}. ${q.question}`,
      '',
      `**${p.keyCorrect}: ${OPTION_LETTERS[q.correctIndex]})** ${q.options[q.correctIndex]}`,
      '',
      `_${p.keyWhy}:_ ${q.explanation}`,
      '',
    );
  });
  return lines.join('\n');
}

/** Erzeugt das Schulungshandout (Kernregeln aus den Erklärungen) als Markdown. */
export function handoutDoc(
  pack: ContentPack,
  today: string,
  profile?: CompanyProfile,
  locale: Locale = 'de',
): string {
  const s = docStrings(locale);
  const p = printStrings(locale);
  const company = profile && profile.name.trim() !== '' ? profile.name : '_______________';
  const lines = [
    `# ${p.handoutTitle}`,
    '',
    `**${s.meta.company}:** ${company} · ${s.inventory.asOf}: ${formatDocDate(today, locale)} · Content-Pack v${pack.version}`,
    '',
    s.disclaimer,
    '',
    p.handoutIntro,
    '',
  ];
  getQuiz(locale).forEach((q, i) => {
    lines.push(`## ${i + 1}. ${q.question}`, '', q.explanation, '');
  });
  lines.push(p.handoutFooter);
  return lines.join('\n');
}

/**
 * Erzeugt das druckbare Schulungsregister (alle Testdurchläufe) als Markdown.
 */
export function trainingLogDoc(
  records: readonly TrainingRecord[],
  pack: ContentPack,
  today: string,
  profile?: CompanyProfile,
  locale: Locale = 'de',
): string {
  const s = docStrings(locale);
  const c = certStrings(locale);
  const company = profile && profile.name.trim() !== '' ? profile.name : '_______________';
  const lines = [
    `# ${c.logTitle}`,
    '',
    `**${s.meta.company}:** ${company} · ${s.inventory.asOf}: ${formatDocDate(today, locale)} · Content-Pack v${pack.version}`,
    '',
    s.disclaimer,
    '',
    c.logIntro.replace('{pct}', String(QUIZ_PASS_PCT)),
    '',
    c.logCols,
    '|---|---|---|---|',
  ];
  for (const r of records) {
    lines.push(
      `| ${formatDocDate(r.date, locale)} | ${r.name} | ${r.scorePct} % | ${r.passed ? c.resultPassed : c.resultFailed} |`,
    );
  }
  return lines.join('\n');
}
