"""
AI Processing - Print Version Generator: Q&A.

Generates printable HTML for question-answer worksheets.
"""

from pathlib import Path
import json
import logging

from .core import BEREINIGT_DIR

logger = logging.getLogger(__name__)


def generate_print_version_qa(qa_path: Path, include_answers: bool = False) -> Path:
    """
    Generiert eine druckbare HTML-Version der Frage-Antwort-Paare.

    Args:
        qa_path: Pfad zur *_qa.json Datei
        include_answers: True fuer Loesungsblatt (fuer Eltern)

    Returns:
        Pfad zur generierten HTML-Datei
    """
    if not qa_path.exists():
        raise FileNotFoundError(f"Q&A-Datei nicht gefunden: {qa_path}")

    qa_data = json.loads(qa_path.read_text(encoding="utf-8"))
    items = qa_data.get("qa_items", [])
    metadata = qa_data.get("metadata", {})

    title = metadata.get("source_title", "Arbeitsblatt")
    subject = metadata.get("subject", "")
    grade = metadata.get("grade_level", "")

    html_parts = []
    html_parts.append("""<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<title>""" + title + """ - Fragen</title>
<style>
  @media print {
    .no-print { display: none; }
    .page-break { page-break-before: always; }
  }
  body {
    font-family: Arial, sans-serif;
    max-width: 800px;
    margin: 40px auto;
    padding: 20px;
    line-height: 1.6;
  }
  h1 { font-size: 24px; margin-bottom: 8px; }
  .meta { color: #666; margin-bottom: 24px; }
  .question-block {
    margin-bottom: 32px;
    padding-bottom: 16px;
    border-bottom: 1px dashed #ccc;
  }
  .question-number {
    font-weight: bold;
    color: #333;
  }
  .question-text {
    font-size: 16px;
    margin: 8px 0;
  }
  .answer-space {
    border: 1px solid #ddd;
    min-height: 60px;
    margin-top: 12px;
    background: #fafafa;
  }
  .answer-lines {
    margin-top: 12px;
  }
  .answer-line {
    border-bottom: 1px solid #999;
    height: 28px;
  }
  .answer {
    margin-top: 8px;
    padding: 8px;
    background: #e8f5e9;
    border-left: 3px solid #4caf50;
  }
  .key-terms {
    font-size: 12px;
    color: #666;
    margin-top: 8px;
  }
  .key-terms span {
    background: #fff3e0;
    padding: 2px 6px;
    border-radius: 3px;
    margin-right: 4px;
  }
</style>
</head>
<body>
""")

    # Header
    version_text = "Loesungsblatt" if include_answers else "Fragenblatt"
    html_parts.append(f"<h1>{title} - {version_text}</h1>")
    meta_parts = []
    if subject:
        meta_parts.append(f"Fach: {subject}")
    if grade:
        meta_parts.append(f"Klasse: {grade}")
    meta_parts.append(f"Anzahl Fragen: {len(items)}")
    html_parts.append(f"<div class='meta'>{' | '.join(meta_parts)}</div>")

    # Fragen
    for idx, item in enumerate(items, 1):
        html_parts.append("<div class='question-block'>")
        html_parts.append(f"<div class='question-number'>Frage {idx}</div>")
        html_parts.append(f"<div class='question-text'>{item.get('question', '')}</div>")

        if include_answers:
            # Loesungsblatt: Antwort anzeigen
            html_parts.append(f"<div class='answer'><strong>Antwort:</strong> {item.get('answer', '')}</div>")
            # Schluesselbegriffe
            key_terms = item.get("key_terms", [])
            if key_terms:
                terms_html = " ".join([f"<span>{term}</span>" for term in key_terms])
                html_parts.append(f"<div class='key-terms'>Wichtige Begriffe: {terms_html}</div>")
        else:
            # Fragenblatt: Antwortlinien
            html_parts.append("<div class='answer-lines'>")
            for _ in range(3):
                html_parts.append("<div class='answer-line'></div>")
            html_parts.append("</div>")

        html_parts.append("</div>")

    html_parts.append("</body></html>")

    # Speichern
    suffix = "_qa_solutions.html" if include_answers else "_qa_print.html"
    out_name = qa_path.stem.replace("_qa", "") + suffix
    out_path = BEREINIGT_DIR / out_name
    out_path.write_text("\n".join(html_parts), encoding="utf-8")

    logger.info(f"Print-Version gespeichert: {out_path.name}")
    return out_path
