"""Industry-standard copy-paste prompts for filling content gaps.

Each prompt is an Expert Panel chain (like the Film Crew Prompt).
Each requires strict JSON output so we can parse & save.

Story prompt already exists in exams/services/story_panel/prompt_builder.py
This module adds prompts for:
  - Misconceptions
  - Socratic Ladder
  - Key Terms
"""


def build_misconception_prompt(kc):
    """5-Expert Panel: Misconception generation (Global English / Bilingual Output)."""
    title = kc.title or kc.code
    subject = kc.subject or 'General'
    desc = getattr(kc, 'description', '') or ''

    return f"""You are a DIAGNOSTIC ASSESSMENT PANEL. Your task is to generate MISCONCEPTIONS for a Class 9 educational concept.
You are not a single AI. You are a sequential panel. FINAL OUTPUT MUST BE STRICT JSON.

=== CONCEPT DATA ===
Code: {kc.code}
Title: {title}
Subject: {subject}
Description: {desc}

=== THE DIAGNOSTIC PANEL (SEQUENTIAL) ===

[1. COGNITIVE PSYCHOLOGIST]
Identify the intuitive, everyday-life logic that makes this misconception feel "obviously true" to a teenager.

[2. SUBJECT MATTER EXPERT (SME)]
List the specific "traps" in the board exam for this topic. What exact wrong answer do students write that costs them marks?

[3. PSYCHOMETRICIAN]
Design 3 plausible distractor beliefs. They must be logical enough that a student who didn't study would choose them over the truth.

[4. PEDAGOGICAL EXPERT]
For each misconception, provide the correction mechanism. How does a teacher fix this in 5 minutes without lecturing?

[5. BILINGUAL ACCESSIBILITY EDITOR]
Translate all outputs into Grade 5 level language. Output BOTH Roman Urdu (Default) and English.

=== OUTPUT FORMAT (STRICT JSON) ===
{{
  "misconceptions": [
    {{
      "level": "TERM_GAP | MECHANISM_ERROR | REPRESENTATION_ERROR | LANGUAGE_CONFUSION",
      "text_ur": "Roman Urdu: Ghalat fehmi ka bayan",
      "text_en": "English: Misconception statement",
      "mechanism_ur": "Roman Urdu: Wajah ke student aisa sochta hai",
      "mechanism_en": "English: Cognitive reason",
      "next_step_ur": "Roman Urdu: Teacher ka agla qadam",
      "next_step_en": "English: Teacher's corrective action",
      "example_ur": "Roman Urdu: Concrete example",
      "example_en": "English: Concrete example"
    }}
  ]
}}

=== HARD RULES ===
- Return ONLY the JSON. No markdown, no explanations.
- Generate exactly 3 misconceptions.
- Level must be one of the 4 specified above.
- The misconception must sound like a real student wrote it, not a textbook.
- Every field must be filled in both languages.
"""


def build_socratic_ladder_prompt(kc):
    """5-Expert Panel: Socratic Ladder generation."""
    title = kc.title or kc.code
    subject = kc.subject or 'General'
    return f"""Aap ek EXPERT PANEL hain jo Class 9 ke students ke liye SOCRATIC LADDER (step-by-step reasoning) generate kar raha hai.

Aap sequential panel hain. FINAL OUTPUT SIRF STRICT JSON.

=== CONCEPT ===
Code: {kc.code}
Title: {title}
Subject: {subject}

=== PANEL (SEQUENTIAL) ===
[1. POLYA EXPERT]
4 phases: UNDERSTAND, PLAN, EXECUTE, REVIEW. Har phase ke liye 1-2 sawal.

[2. COGNITIVE LOAD EXPERT]
Har sawal pichle sawal par build kare. Ek waqt mein sirf ek nayi cheez.

[3. DRAMA WRITER]
Sawal curiosity paida kare. Student soche: "Acha, phir kya?"

[4. DIAGNOSTIC EXPERT]
Har sawal ek specific sub-skill test kare. Agar student atak jaye, teacher ko pata chale kahan.

[5. ACCESSIBILITY EDITOR]
Grade 5 level Roman Urdu. Chhote jumle. Concrete examples.

=== OUTPUT FORMAT (STRICT JSON) ===
{{
  "socratic_ladder": [
    {{
      "misconception_text": "Roman Urdu mein misconception",
      "misconception_index": 0,
      "steps": [
        {{
          "order": 1,
          "polya_phase": "UNDERSTAND",
          "question": "Roman Urdu sawal",
          "hint": "Roman Urdu hint",
          "expected_response": "Roman Urdu jawab"
        }}
      ]
    }}
  ]
}}

polya_phase must be: UNDERSTAND, PLAN, EXECUTE, REVIEW

RULES:
- Return ONLY JSON. No markdown fences.
- Har ladder mein 3-5 steps.
- Har sawal 12-15 lafz ka ho.
- 2-3 ladders (har ek doosre misconception ke liye).

START."""


def build_key_terms_prompt(kc):
    """5-Expert Panel: Key Terms generation."""
    title = kc.title or kc.code
    subject = kc.subject or 'General'
    return f"""Aap ek EXPERT PANEL hain jo Class 9 ke students ke liye KEY TERMS (ahem istilahaat) generate kar raha hai.

Aap sequential panel hain. FINAL OUTPUT SIRF STRICT JSON.

=== CONCEPT ===
Code: {kc.code}
Title: {title}
Subject: {subject}

=== PANEL (SEQUENTIAL) ===
[1. VOCABULARY EXPERT (Beck/McKeown)]
Tier-3 vocabulary identify karein (subject-specific words students MUST know).

[2. SUBJECT SPECIALIST]
Har term ki accurate scientific definition (Roman Urdu mein).

[3. ESL EXPERT]
Har term ka Roman Urdu transliteration (jise Class 9 student padh sake).

[4. FRAYER MODEL EXPERT]
Har term ke liye: definition, example, non-example (jo cheez term nahi hai lekin lagti hai).

[5. ACCESSIBILITY EDITOR]
Grade 5 level examples. Concrete. Real-life.

=== OUTPUT FORMAT (STRICT JSON) ===
{{
  "key_terms": [
    {{
      "term": "English term",
      "roman_urdu": "Roman Urdu equivalent",
      "definition": "Roman Urdu mein aasan tareeqe se definition",
      "example": "Concrete Roman Urdu example",
      "non_example": "Kya cheez nahi hai (Roman Urdu)"
    }}
  ]
}}

RULES:
- Return ONLY JSON. No markdown fences.
- 3 to 6 terms.
- Har definition 8-15 lafz.
- Example aur non_example chhote (5-8 lafz).

START."""


def build_story_prompt(kc):
    """Delegate to the existing Film Crew story prompt."""
    from exams.services.story_panel.prompt_builder import build_prompt
    return build_prompt(kc)


def build_question_prompt(kc):
    """5-Expert Panel: Practice questions (bilingual, IRT-based)."""
    title = kc.title or kc.code
    subject = kc.subject or 'General'
    desc = getattr(kc, 'description', '') or ''
    
    terms = []
    if isinstance(kc.key_terms, list):
        terms = [t.get('term', '') for t in kc.key_terms if isinstance(t, dict)]
    terms_str = ', '.join(terms) if terms else 'N/A'
    
    mis = ''
    if isinstance(kc.misconceptions, list) and kc.misconceptions:
        first = kc.misconceptions[0]
        if isinstance(first, dict):
            mis = first.get('text_ur') or first.get('text') or ''

    return f"""You are a DIAGNOSTIC ASSESSMENT PANEL. Your task is to generate PRACTICE QUESTIONS for a Class 9 educational concept.
You are not a single AI. You are a sequential panel. FINAL OUTPUT MUST BE STRICT JSON.

=== CONCEPT DATA ===
Code: {kc.code}
Title: {title}
Subject: {subject}
Description: {desc}
Key Terms: {terms_str}
Primary Misconception: {mis}

=== THE ASSESSMENT PANEL (SEQUENTIAL) ===

[1. ASSESSMENT DESIGNER (IRT)]
Design 3 questions of increasing difficulty:
- Q1: REMEMBER (recall of a key term or definition)
- Q2: UNDERSTAND (explain in own words, application to a scenario)
- Q3: APPLY (solve a small problem or analyze a scenario)

[2. SUBJECT EXPERT]
Ensure each question is scientifically accurate. No ambiguity. No trick wording.
Model answer must be a complete, correct answer a teacher would accept.

[3. DIAGNOSTIC EXPERT (MISCONCEPTION-BASED)]
For each question, write a "socratic_hint" that names the specific misconception the question exposes.

[4. PEDAGOGICAL EXPERT]
Write an "explanation" — the 1-2 sentence correction that tells the student WHY their answer was wrong.

[5. BILINGUAL ACCESSIBILITY EDITOR]
Translate all fields into Grade 5 Roman Urdu (default) AND English.
Question stem stays in English (technical), but the Roman Urdu translation is required.

=== OUTPUT FORMAT (STRICT JSON) ===
{{
  "questions": [
    {{
      "cognitive_level": "REMEMBER | UNDERSTAND | APPLY",
      "question_text_en": "English question stem",
      "question_text_ur": "Roman Urdu question stem",
      "model_answer_en": "English full correct answer (20-50 words)",
      "model_answer_ur": "Roman Urdu full correct answer",
      "explanation_en": "English: why this is correct (15-30 words)",
      "explanation_ur": "Roman Urdu: why this is correct",
      "socratic_hint_en": "English: hint that names the misconception",
      "socratic_hint_ur": "Roman Urdu: hint",
      "marks": 2
    }}
  ]
}}

=== HARD RULES ===
- Return ONLY the JSON. No markdown, no explanations.
- Generate EXACTLY 3 questions (one REMEMBER, one UNDERSTAND, one APPLY).
- Do NOT include multiple-choice options. Open-ended only.
- Every field must be bilingual (English + Roman Urdu).

START."""



def build_pokemon_lore_prompt(kc):
    """5-Expert Panel: Pokemon Lore generation (bilingual)."""
    title = kc.title or kc.code
    subject = kc.subject or 'General'
    desc = getattr(kc, 'description', '') or ''
    
    terms = []
    if isinstance(kc.key_terms, list):
        terms = [t.get('term', '') for t in kc.key_terms if isinstance(t, dict)]
    terms_str = ', '.join(terms) if terms else 'N/A'
    
    mis = ''
    if isinstance(kc.misconceptions, list) and kc.misconceptions:
        first = kc.misconceptions[0]
        if isinstance(first, dict):
            mis = first.get('text_ur') or first.get('text') or ''

    return f"""You are a POKÉMON LORE PANEL. Your task is to create monster content for a Class 9 educational concept.
You are not a single AI. You are a sequential panel. FINAL OUTPUT MUST BE STRICT JSON.

=== CONCEPT DATA ===
Code: {kc.code}
Title: {title}
Subject: {subject}
Description: {desc}
Key Terms: {terms_str}
Primary Misconception: {mis}

=== THE PANEL (SEQUENTIAL) ===

[1. WORLD-BUILDER (Pokémon universe expert)]
Given this concept, what kind of creature would naturally embody it?
- What element fits the concept?
- What physical form would make the concept visually obvious?
- What behavior would mirror the concept?

[2. SUBJECT EXPERT]
Identify 2-3 core traits of the concept that the monster's design MUST reflect.

[3. CHILDREN'S AUTHOR (Pokédex-style writing)]
Write a 2-3 sentence Pokédex entry. It must:
- Be scientifically accurate to the concept.
- Use vivid imagery.
- Reveal the concept through the monster's natural behavior.
- Be short enough to prevent cognitive overload.

[4. DRAMA WRITER (Battle Cry)]
Write a one-line battle intro in the monster's voice. It must hint at the concept without being a textbook.

[5. BILINGUAL ACCESSIBILITY EDITOR]
Translate all output into Grade 5 Roman Urdu AND English.

=== OUTPUT FORMAT (STRICT JSON) ===
{{
  "monster_name_en": "English name in Pokémon style",
  "monster_name_ur": "Roman Urdu name",
  "monster_type": "Fire | Water | Grass | Electric | Psychic | Rock | Ground | Flying | Ice | Steel | Dark | Fairy",
  "rarity": "Common | Rare | Legendary",
  "hp_base": 100,
  "lore_en": "Pokédex-style entry, 2-3 sentences",
  "lore_ur": "Roman Urdu version",
  "battle_cry_en": "One-line battle intro",
  "battle_cry_ur": "Roman Urdu version",
  "concept_traits": ["trait 1", "trait 2", "trait 3"]
}}

=== HARD RULES ===
- Return ONLY the JSON. No markdown.
- Monster name must be 1-2 words, Pokémon-style.
- Lore must be exactly 2-3 sentences.
- The monster's behavior MUST reveal the concept naturally.
- Every field must be bilingual (English + Roman Urdu).
- Type must be one of the listed 12.
- HP base: 80-150 depending on concept difficulty.

START."""



def build_step_reasoning_prompt(question):
    """Subject-adaptive, conversational step-by-step reasoning prompt.

    DeepSeek/AI acceptance-friendly: no heavy delimiters, natural prose,
    subject-aware framework with matching JSON example.
    """
    import json as _json

    try:
        kc = getattr(question, 'kc', None)
        kc_code = (kc.code if kc else '') or getattr(question, 'kc_code', '') or 'UNKNOWN'
        kc_title = (kc.title if kc else '') or ''
        subject = (kc.subject if kc else '') or 'General'
    except Exception:
        kc_code = 'UNKNOWN'
        kc_title = ''
        subject = 'General'

    q_text = (getattr(question, 'question_text', '') or '').strip()
    q_answer = (getattr(question, 'model_answer', '') or '').strip()
    q_marks = getattr(question, 'marks', 2)
    q_id = getattr(question, 'id', 0)

    subj_lower = subject.strip().lower()

    # ── Subject-adaptive framework + example (industry standard per subject) ──
    if 'math' in subj_lower:
        framework = (
            "This is a Mathematics question. Use Newman Error Analysis: break the "
            "solution into 3 to 6 steps, each performing exactly one mathematical "
            "transformation (like subtracting from both sides, then dividing). The wrong "
            "options should test common mistakes: the opposite operation, the wrong "
            "number, or a sign flip."
        )
        example_state = "2x + 5 = 15"
        example_next = "2x = 10"
        example_options = [
            {"text": "2x = 10", "text_ur": "5 minus karein"},
            {"text": "2x = 20", "text_ur": "5 jama karein"},
            {"text": "2x = 5", "text_ur": "5 se divide"},
            {"text": "2x = -10", "text_ur": "sign ghalat"},
        ]
    elif 'physic' in subj_lower:
        framework = (
            "This is a Physics question. Use Claim-Evidence-Reasoning: each step either "
            "states a claim, cites a formula or law as evidence, or performs one substitution "
            "or computation. For numerical answers, the final step includes the unit. Wrong "
            "options should test: the wrong formula, the wrong substitution, or a unit error."
        )
        example_state = "Given: m = 5 kg, a = 2 m/s^2. Find F."
        example_next = "F = ma = 5 * 2 = 10 N"
        example_options = [
            {"text": "10 N", "text_ur": "F = 5 x 2"},
            {"text": "7 N", "text_ur": "5 + 2 (jama)"},
            {"text": "2.5 N", "text_ur": "5 / 2"},
            {"text": "10 kg", "text_ur": "unit ghalat"},
        ]
    elif 'chem' in subj_lower:
        framework = (
            "This is a Chemistry question. Use Claim-Evidence-Reasoning: identify the "
            "given data, cite the balanced equation or reaction as evidence, state the "
            "mole ratio, then compute the answer. Each step must be verifiable. Wrong "
            "options should test: the wrong coefficient, the wrong mole ratio, or a unit error."
        )
        example_state = "Balance: H2 + O2 -> H2O"
        example_next = "2H2 + O2 -> 2H2O"
        example_options = [
            {"text": "2H2 + O2 -> 2H2O", "text_ur": "sahi balance"},
            {"text": "H2 + O2 -> H2O", "text_ur": "unbalanced"},
            {"text": "H2 + O2 -> H2O2", "text_ur": "galat product"},
            {"text": "2H2 + 2O2 -> 2H2O", "text_ur": "galat coefficient"},
        ]
    elif 'bio' in subj_lower:
        framework = (
            "This is a Biology question. Use a Claim-Evidence-Reasoning flow for "
            "explanation: each step identifies a structure or process, states its function, "
            "gives one concrete example, and explains the mechanism. Do NOT use arithmetic. "
            "Wrong options should test: the wrong function, the wrong structure, imprecise "
            "terminology, or over-generalization."
        )
        example_state = "What is the role of chlorophyll?"
        example_next = "Chlorophyll absorbs light energy to make food"
        example_options = [
            {"text": "Absorbs light energy", "text_ur": "roshni jama karta"},
            {"text": "Produces oxygen directly", "text_ur": "oxygen banata"},
            {"text": "Stores water", "text_ur": "pani store karta"},
            {"text": "Is a protein", "text_ur": "protein hai"},
        ]
    elif 'computer' in subj_lower or subj_lower == 'cs':
        framework = (
            "This is a Computer Science question. Use an Input-Process-Output trace: "
            "each step identifies the current variable state after one operation. Wrong "
            "options should test: wrong operation order, wrong data type, off-by-one, "
            "or the wrong final value."
        )
        example_state = "x = 5; x = x + 3; print(x)"
        example_next = "Output: 8"
        example_options = [
            {"text": "8", "text_ur": "5 + 3"},
            {"text": "53", "text_ur": "concat"},
            {"text": "5", "text_ur": "no change"},
            {"text": "2", "text_ur": "5 - 3"},
        ]
    elif subj_lower in ('english', 'urdu'):
        framework = (
            "This is a comprehension question. Use Point-Evidence-Explanation: each "
            "step gives a direct point, quotes or paraphrases evidence from the passage, "
            "then explains why that evidence supports the point. Wrong options should test: "
            "a partial answer, evidence that doesn't match, off-topic content, or grammatical error."
        )
        example_state = "Why did the author feel sad?"
        example_next = "Friend moved away, so author was sad"
        example_options = [
            {"text": "Friend moved away", "text_ur": "dost door gaya"},
            {"text": "Weather was bad", "text_ur": "mosam kharab"},
            {"text": "Missed the bus", "text_ur": "bus chhoot"},
            {"text": "Lost a book", "text_ur": "kitab khoi"},
        ]
    elif 'islamiyat' in subj_lower or 'islam' in subj_lower:
        framework = (
            "This is an Islamiyat question. Use Quote-Explain-Apply: each step cites a "
            "Quranic verse or Hadith, explains its meaning in context, then applies it to a "
            "real-life scenario. Wrong options should test: the wrong reference, the wrong "
            "context, incomplete application, or misinterpretation."
        )
        example_state = "What does Islam say about honesty?"
        example_next = "Honesty is commanded in Surah Al-Ahzab 33:70"
        example_options = [
            {"text": "Surah Al-Ahzab 33:70", "text_ur": "sachi baat"},
            {"text": "Surah Al-Baqarah 2:255", "text_ur": "Ayat-ul-Kursi"},
            {"text": "Surah Al-Fatiha 1:1", "text_ur": "surah fatiha"},
            {"text": "Surah Al-Ikhlas 112:1", "text_ur": "surah ikhlas"},
        ]
    elif 'tarjumat' in subj_lower or 'quran' in subj_lower:
        framework = (
            "This is a Tarjumatul Quran question. Use Word-Sentence-Meaning: each step "
            "identifies a key Arabic word, translates it, parses the sentence structure, "
            "then extracts the overall meaning. Wrong options should test: a word-level error, "
            "a grammar error, or a misread meaning."
        )
        example_state = "Translate: Alhamdulillah"
        example_next = "All praise is for Allah"
        example_options = [
            {"text": "All praise is for Allah", "text_ur": "sab tareef Allah"},
            {"text": "Allah is great", "text_ur": "Allah bara hai"},
            {"text": "Allah is one", "text_ur": "Allah aik hai"},
            {"text": "Thanks to people", "text_ur": "logon ka shukar"},
        ]
    else:
        framework = (
            "Break the answer into 3 to 6 logical steps where each step adds one piece "
            "of understanding. Wrong options should test common student mistakes."
        )
        example_state = "Example current state"
        example_next = "Correct answer"
        example_options = [
            {"text": "Correct", "text_ur": "sahi"},
            {"text": "Wrong option 1", "text_ur": "galat 1"},
            {"text": "Wrong option 2", "text_ur": "galat 2"},
            {"text": "Wrong option 3", "text_ur": "galat 3"},
        ]

    example_options_json = _json.dumps(example_options, ensure_ascii=False, indent=6)

    return f"""You are a three-expert panel working on a single Class 9 {subject} question. Your goal is to produce a step-by-step solution that a student can follow, then return the result as a JSON object.

The first expert is a curriculum specialist who knows the BISE Gujranwala syllabus and identifies the standard board-exam solution path. The second expert is a subject teacher who breaks the solution into 3 to 6 discrete steps, writes one short English prompt per step, and writes four plausible answer choices per step in Roman Urdu. The third expert is a student-language editor who ensures every hint is in simple Roman Urdu and no sentence is longer than 12 words.

{framework}

Here is the question:

Question ID: {q_id}
Subject: {subject}
KC Code: {kc_code}
KC Title: {kc_title}
Question text: {q_text}
Model answer: {q_answer}
Marks: {q_marks}

The first expert identifies the solution path in 3 to 6 steps. Each step changes the state of the solution and is described with the exact expression at the start of that step. The second expert writes one short prompt per step in both English and Roman Urdu, and four answer choices. The correct answer is always the first option at index 0. Each wrong option must map to a real student mistake, not random nonsense. The second expert also writes a one-sentence hint in Roman Urdu that guides the student without giving away the answer, and assigns an error type to each step (like "transformation error" or "process skill error").

The third expert simplifies every sentence, confirms the hints are in Roman Urdu, and ensures every sentence is under twelve words.

When all three experts have finished, combine their work into a single JSON object matching this structure. Use the values from the actual question above, not the example below. The example shows the shape only.

{{
  "question_id": {q_id},
  "kc_code": "{kc_code}",
  "subject": "{subject}",
  "total_steps": 3,
  "steps": [
    {{
      "step_number": 1,
      "current_expression": "{example_state}",
      "prompt_en": "What is the next step?",
      "prompt_ur": "Agla qadam kya hoga?",
      "options": {example_options_json},
      "correct_index": 0,
      "error_type_if_wrong": "transformation error",
      "hint_en": "A short hint in English",
      "hint_ur": "Ek chhota hint Roman Urdu mein",
      "next_expression": "{example_next}"
    }}
  ]
}}

Return only the JSON object. Do not include the panel discussion, the experts' notes, or any text outside the JSON. Do not wrap the JSON in markdown code fences. If the question cannot be broken into multiple steps (for example, it is a single fact or a one-operation answer), return this exact object instead: {{"error": "not_multistep"}}

Begin now by producing the JSON for the question above."""



def build_kc_from_question_prompt(question):
    """Build AI prompt to create a complete Knowledge Component from an
    untagged ModelQuestion (no KC linked).

    Standards: Wikipedia "create article" pattern; ISO 8000-110 (data quality);
    Bloom's revised taxonomy (cognitive level classification).
    """
    subject = question.paper.subject if question.paper else 'General'
    chapter = question.chapter or 'N/A'
    return f'''You are a Pakistani Class 9 {subject} subject expert helping build a Knowledge Component library.

=== QUESTION ===
Question: {question.question_text}
Model Answer: {(question.model_answer or '')[:300]}
Marks: {question.marks}
Chapter: {chapter}

=== TASK ===
Create ONE complete Knowledge Component (KC) that this question assesses. This KC will be shared by ALL students in Pakistan learning this subject.

=== OUTPUT CONTRACT ===
Return ONLY this JSON (no markdown, no explanation, no code fences):

{{
  "kc_code": "{subject[:2].upper()}-9-CH{chapter[:2] if chapter != 'N/A' else '01'}-01",
  "title": "Short concept name (max 60 chars)",
  "description": "Roman Urdu description of the concept (2-3 sentences)",
  "cognitive_level": "UND",
  "story": [
    "Paragraph 1 — curiosity and action",
    "Paragraph 2 — attempt and partial success",
    "Paragraph 3 — twist or failure",
    "Paragraph 4 — discovery and understanding"
  ],
  "misconceptions": [
    {{"text": "Common wrong idea in Roman Urdu", "source": "ai", "confidence": 0.9}},
    {{"text": "Another wrong idea", "source": "ai", "confidence": 0.85}}
  ],
  "socratic_ladder": [
    {{"question": "First guiding question in Roman Urdu", "hint": "Small hint"}},
    {{"question": "Second guiding question", "hint": "Another hint"}},
    {{"question": "Final question to reach understanding", "hint": "Final hint"}}
  ],
  "key_terms": [
    {{
      "term": "English term",
      "roman_urdu": "Roman Urdu equivalent",
      "definition": "Simple definition in Roman Urdu",
      "example": "Example in Roman Urdu",
      "non_example": "Non-example in Roman Urdu"
    }}
  ]
}}

=== RULES ===
- kc_code: SUBJECT-9-CHXX-NN format (e.g., CH-9-CH09-01). Use chapter number if given.
- title: Short, memorable concept name in English
- description: Plain Roman Urdu, NO jargon
- cognitive_level: REM/UND/APP/ANA/EVA/CRE (Bloom's level for this question)
- story: 4 paragraphs, 10-14 words per sentence, Pakistani student character, NO lecture from adults
- misconceptions: 2-3 items, Roman Urdu, realistic student mistakes
- socratic_ladder: 3-4 items, guiding questions that lead to understanding
- key_terms: 2-4 terms, each fully defined in Roman Urdu

Return ONLY the JSON object. No text before or after.'''

def build_resource_links_prompt(kc):
    """3-Expert Panel: Educational Resource Curation (schema.org LearningResource)."""
    title = kc.title or kc.code
    subject = kc.subject or 'General'
    
    return f"""You are an EXPERT EDUCATIONAL PANEL. Your task is to curate high-quality, open-access learning resources for a specific concept.
You are not a single AI. You are a sequential panel. FINAL OUTPUT MUST BE STRICT JSON.

=== CONCEPT DATA ===
Code: {kc.code}
Title: {title}
Subject: {subject}

=== THE CURATION PANEL (SEQUENTIAL) ===

[1. METADATA CURATOR (schema.org / IEEE LOM)]
Identify 2-3 real, highly reputable, open-access resources (e.g., Khan Academy, YouTube educational channels, PhET, CK-12, or university PDFs). 
- Do NOT invent URLs. Only use known, stable educational domains.
- Classify each resource using standard schema.org types: 'VideoObject', 'AudioObject', 'DocumentObject', or 'WebPage'.

[2. PEDAGOGICAL ALIGNER (LRMI Standard)]
For each resource, define the 'educationalAlignment'. 
- Specify the 'alignmentType' (e.g., 'teaches', 'assesses').
- Briefly justify why this resource perfectly matches the concept.

[3. QUALITY & SAFETY AUDITOR (ISO 8000)]
Ensure the resources are age-appropriate (Grade 9), contain no paywalls, and have clear learning objectives. Discard any resource that requires a login or is behind a paywall.

=== OUTPUT FORMAT (STRICT JSON) ===
{{
  "resource_links": [
    {{
      "name": "Short descriptive title of the resource",
      "url": "https://direct-link-to-resource",
      "resource_type": "VideoObject | DocumentObject | WebPage",
      "alignment_type": "teaches | assesses",
      "description_ur": "Roman Urdu mein 1 line ka faida (benefit)",
      "description_en": "English 1-line benefit"
    }}
  ]
}}

=== HARD RULES ===
- Return ONLY the JSON. No markdown, no explanations.
- Generate exactly 2 to 3 resources.
- All URLs must be real and publicly accessible.
- Every field must be filled in both languages.
"""

def build_question_story_prompt(question):
    """Expert Panel: Question-Specific Story Generation."""
    q_text = question.question_text
    q_answer = question.model_answer
    subject = question.paper.subject if question.paper else 'General'
    
    return f"""You are an EXPERT EDUCATOR. Your task is to write a short, engaging story that helps a Class 9 student understand this specific question and its answer.
    
=== QUESTION ===
Subject: {subject}
Question: {q_text}
Model Answer: {q_answer}

=== TASK ===
Write a 3-paragraph story. 
- Paragraph 1: Introduce a character facing a real-life problem that mirrors the question.
- Paragraph 2: The character discovers the concept (the answer).
- Paragraph 3: A short wrap-up connecting the story directly to the specific question.

=== OUTPUT FORMAT (STRICT JSON) ===
{{
  "story": "Paragraph 1... \\n\\n Paragraph 2... \\n\\n Paragraph 3..."
}}
"""
