"""Template auto-detection — detect question type from text content.

Automatically classifies input text as MCQ, code, translation, grammar,
or general to select the optimal system prompt.
"""

from __future__ import annotations

import re


def detect_template(text: str) -> str:
    """Detect question type from text content.

    Returns:
        One of: "mcq", "mcq_multi", "true_false", "code", "code_debug",
        "translation", "grammar", "email_reply", "general"
    """
    stripped = text.strip()
    if not stripped:
        return "general"

    text_lower = stripped.lower()

    # True/False detection — before MCQ to avoid misclassification
    tf_hints = [
        "верно или неверно",
        "true or false",
        "истина или ложь",
        "да или нет",
        "правда или нет",
        "верно/неверно",
        "true/false",
        "对还是错",
        "判断题",
        "判断对错",
    ]
    tf_options = ["true", "false", "верно", "неверно", "да", "нет", "истина", "ложь"]
    tf_option_count = sum(1 for o in tf_options if o in text_lower)
    if any(h in text_lower for h in tf_hints) or tf_option_count >= 2:
        return "mcq"  # reuse MCQ prompt — AI returns A or B for True/False

    # MCQ: contains option letters like "A." "B)" "A:" or "(A)"
    # Also supports Cyrillic: А) Б) В) Г) and Chinese: A、B、C、D
    mcq_markers = [
        "а)",
        "б)",
        "в)",
        "г)",
        "а.",
        "б.",
        "в.",
        "г.",
        "a)",
        "b)",
        "c)",
        "d)",
        "a.",
        "b.",
        "c.",
        "d.",
        "1)",
        "2)",
        "3)",
        "4)",
    ]
    mcq_score = sum(1 for m in mcq_markers if m in text_lower)
    if mcq_score >= 3:
        # Multi-select MCQ detection
        multi_hints = [
            "несколько вариантов",
            "несколько правильных",
            "все верные",
            "все правильные",
            "выберите все",
            "select all",
            "multiple correct",
            "multiple answers",
            "all that apply",
            "check all",
            "多选",
            "全选",
        ]
        if any(h in text_lower for h in multi_hints):
            return "mcq_multi"
        return "mcq"

    if re.search(r"(?m)^\s*[A-Da-d][.):\s]", stripped):
        return "mcq"
    if re.search(r"\([A-Da-d]\)", stripped):
        return "mcq"
    # Chinese-style options: A、B、C、D
    if re.search(r"[A-D]\u3001", stripped):
        return "mcq"

    # Code detection with sub-classification
    code_markers = [
        "def ",
        "class ",
        "function ",
        "import ",
        "from ",
        "return ",
        "if __name__",
        "console.log",
        "System.out",
        "public static",
        "int main(",
        "void ",
        "#include",
        "SELECT ",
        "INSERT ",
        "CREATE TABLE",
        "const ",
        "let ",
        "var ",
        "=>",
        "->",
    ]
    code_score = sum(1 for marker in code_markers if marker in stripped)
    # SQL statements are recognizable with just 1 marker
    sql_markers = ["SELECT ", "INSERT ", "CREATE TABLE", "ALTER TABLE", "DROP TABLE"]
    has_sql = any(m in stripped for m in sql_markers)
    is_code = code_score >= 2 or has_sql or stripped.startswith(("```", "#!/"))
    if not is_code and re.search(r"[{};]\s*\n", stripped) and len(stripped) > 20:
        is_code = True

    if is_code:
        error_hints = [
            "error",
            "bug",
            "fix",
            "issue",
            "traceback",
            "exception",
            "ошибк",
            "баг",
            "исправ",
            "错误",
            "修复",
        ]
        if any(h in text_lower for h in error_hints):
            return "code_debug"
        return "code"

    # Translation: explicit translation request
    translation_markers = [
        "translate",
        "перевод",
        "переведи",
        "翻译",
        "翻譯",
        "traduc",
        "übersetze",
        "traduire",
    ]
    if any(marker in text_lower for marker in translation_markers):
        return "translation"

    # Grammar: check/fix grammar request
    grammar_markers = [
        "grammar",
        "grammaire",
        "grammatik",
        "грамматик",
        "proofread",
        "correct my",
        "fix my english",
        "spell check",
        "check spelling",
    ]
    if any(marker in text_lower for marker in grammar_markers):
        return "grammar"

    # Email detection
    email_indicators = [
        "dear ",
        "hi ",
        "hello ",
        "regards",
        "sincerely",
        "best,",
        "subject:",
        "from:",
        "to:",
    ]
    email_score = sum(1 for ind in email_indicators if ind in text_lower)
    if email_score >= 2:
        return "email_reply"

    return "general"


# System prompts optimized for each detected template type
TEMPLATE_PROMPTS: dict[str, str] = {
    "mcq": (
        "You are an exam assistant. For multiple choice questions, "
        "output ONLY the correct option letter (A, B, C, or D). "
        "Do not explain unless explicitly asked."
    ),
    "mcq_multi": (
        "You are an exam assistant. This is a multiple-select question. "
        "Output ALL correct option letters separated by commas (e.g. A, C, D). "
        "Do not explain unless explicitly asked."
    ),
    "code": (
        "You are a programming assistant. Analyze the code and provide "
        "a clear, concise answer. Include code in your response when appropriate."
    ),
    "code_debug": (
        "You are a debugging expert. Identify the bug or error in the code, "
        "explain the root cause briefly, and provide the corrected code."
    ),
    "translation": (
        "You are a professional translator. Translate the text accurately, "
        "preserving the original meaning, tone, and style."
    ),
    "grammar": (
        "You are a grammar expert. Fix grammar, spelling, and punctuation errors. "
        "Return only the corrected text without explanations."
    ),
    "email_reply": (
        "You are a professional email assistant. Draft a polite, clear, and "
        "appropriate reply to the email. Match the tone and formality of the original."
    ),
    "general": (
        "You are an exam assistant. Answer questions accurately and concisely. "
        "For multiple choice questions, output only the correct option letter. "
        "For open-ended questions, give a clear and precise answer."
    ),
}
