File size: 25,293 Bytes
fa22010
 
 
 
 
 
e20632a
fa22010
 
 
f3a09f2
5e83f9b
fa22010
 
 
 
 
 
 
 
5e83f9b
 
 
e86ac7a
5e83f9b
fa22010
 
 
 
 
 
20e0ed7
 
6a1a0a3
 
 
20e0ed7
 
d0e667a
20e0ed7
 
d0e667a
20e0ed7
20640b8
 
d0e667a
20e0ed7
 
 
 
20640b8
f2decac
 
 
 
 
 
20e0ed7
 
 
20640b8
20e0ed7
 
8efc1c7
20e0ed7
 
d0e667a
20e0ed7
 
d0e667a
20e0ed7
 
 
fa22010
20e0ed7
fa22010
20e0ed7
fa22010
 
 
 
 
 
 
764f6e8
5e83f9b
d08a10a
f3a09f2
5e83f9b
 
f3a09f2
d08a10a
 
 
f3a09f2
5e83f9b
 
f3a09f2
 
764f6e8
 
f3a09f2
5e83f9b
 
 
 
 
 
f3a09f2
5e83f9b
 
 
 
 
 
 
 
 
f3a09f2
 
d228331
fa22010
 
f3a09f2
 
d08a10a
 
f3a09f2
d08a10a
 
 
 
 
 
 
 
 
f3a09f2
 
 
2c5a9b4
5e83f9b
2c5a9b4
 
f3a09f2
5e83f9b
 
 
 
 
 
 
d08a10a
5e83f9b
 
fa22010
5e83f9b
d08a10a
f3a09f2
e86ac7a
5e83f9b
e86ac7a
f3a09f2
fa22010
d228331
5e83f9b
d08a10a
d228331
5e83f9b
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a71a375
 
 
 
8559de8
fa22010
 
a71a375
fa22010
a71a375
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0e667a
 
fa22010
 
 
6a1a0a3
 
 
d0e667a
6a1a0a3
d0e667a
6a1a0a3
d0e667a
 
6a1a0a3
fa22010
 
 
d0e667a
fa22010
 
d0e667a
 
6a1a0a3
d0e667a
 
 
6a1a0a3
d0e667a
 
 
 
 
 
 
 
 
 
 
 
 
 
6a1a0a3
d0e667a
6a1a0a3
d0e667a
 
 
 
fa22010
d0e667a
6a1a0a3
d0e667a
 
 
 
6a1a0a3
fa22010
 
d0e667a
fa22010
 
 
 
 
d0e667a
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a09f2
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a09f2
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a09f2
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a09f2
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a09f2
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a09f2
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a09f2
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a09f2
fa22010
 
 
 
 
 
 
 
f3a09f2
fa22010
 
 
 
 
 
 
 
 
 
 
d0e667a
fa22010
d0e667a
 
 
6a1a0a3
 
d0e667a
 
 
 
 
 
 
 
 
 
 
6a1a0a3
 
d0e667a
fa22010
d0e667a
 
 
 
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3a09f2
fa22010
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
import logging
import random
import traceback
import asyncio
import json
import re
import httpx
from datetime import datetime

from config import (
    GEMINI_MODEL, GEMINI_MAX_TOKENS,
    GEMINI_TEMPERATURE, SUBJECT_ROTATION, GEMINI_API_KEY
)
from content.config_manager import config_manager
from content.syllabus_manager import syllabus_manager
from content.template_manager import template_manager
from content.history import pick_fresh_chapter, archive_weekly_post

logger = logging.getLogger(__name__)

# Initialize Gemini Client check
if not GEMINI_API_KEY:
    logger.warning("⚠️  GEMINI_API_KEY is missing! Bot will not be able to generate content. Add it to .env file.")
else:
    logger.info("βœ… Gemini API configured and ready")


# ─────────────────────────────────────────────
#  Helpers
# ─────────────────────────────────────────────

def _clean_markdown(text: str) -> str:
    """Convert Gemini output to Telegram HTML format."""
    if not text:
        return ""

    import html as html_lib
    import re

    # 1. Unescape any HTML entities first
    text = html_lib.unescape(text)

    # 2. Strip code fences wrapping whole response
    text = re.sub(r'^```(?:json|python|markdown)?\s*\n?', '', text, flags=re.MULTILINE)
    text = re.sub(r'\n?```$', '', text, flags=re.MULTILINE).strip()

    # 3. Escape HTML special chars BEFORE adding our own tags
    text = text.replace('&', '&')
    text = text.replace('<', '&lt;')
    text = text.replace('>', '&gt;')

    # Restore permitted HTML tags that Gemini might have generated (since prompt asks for <b>)
    allowed_tags = ['b', 'i', 'code', 'u', 's', 'pre', 'strong', 'em']
    for tag in allowed_tags:
        text = re.sub(rf'&lt;({tag})&gt;', rf'<\1>', text, flags=re.IGNORECASE)
        text = re.sub(rf'&lt;/({tag})&gt;', rf'</\1>', text, flags=re.IGNORECASE)

    # 4. Convert **bold** or *bold* β†’ <b>bold</b>
    text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', text, flags=re.DOTALL)
    text = re.sub(r'\*([^\*\n]+?)\*', r'<b>\1</b>', text)

    # 5. Convert _italic_ β†’ <i>italic</i>
    text = re.sub(r'_([^_\n]+?)_', r'<i>\1</i>', text)

    # 6. Convert `code` β†’ <code>code</code>
    text = re.sub(r'`([^`]+?)`', r'<code>\1</code>', text)

    # 7. Convert ## Headers β†’ <b>Header</b>
    text = re.sub(r'^#{1,3}\s+(.+)$', r'<b>\1</b>', text, flags=re.MULTILINE)

    # 8. Remove $...$ math delimiters, keep formula text plain
    text = re.sub(r'\$\$(.+?)\$\$', lambda m: m.group(1).strip(), text, flags=re.DOTALL)
    text = re.sub(r'\$([^\$\n]+?)\$', lambda m: m.group(1).strip(), text)

    # 9. Truncate
    if len(text) > 4000:
        text = text[:3997] + "..."

    return text

def _today() -> str:
    return datetime.now().strftime("%A")


async def _call_llm(prompt: str, system_prompt: str = None) -> str:
    """Wrapper for Gemini API using httpx."""
    max_retries = 5  # More retries to handle transient 503 spikes
    
    if not GEMINI_API_KEY:
        raise Exception("GEMINI_API_KEY is missing from config/env. Add it to .env file.")
    
    # Use GEMINI_MODEL from config (not a hardcoded alias that may degrade)
    model = GEMINI_MODEL
    url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent"
    headers = {
        "Content-Type": "application/json",
        "X-goog-api-key": GEMINI_API_KEY
    }
    
    sys_prompt = system_prompt if system_prompt else template_manager.system_prompt
    
    payload = {
        "contents": [
            {
                "parts": [
                    {"text": prompt}
                ]
            }
        ],
        "systemInstruction": {
            "parts": [
                {"text": sys_prompt}
            ]
        },
        "generationConfig": {
            "temperature": GEMINI_TEMPERATURE,
            "maxOutputTokens": GEMINI_MAX_TOKENS
        }
    }
    
    last_error = None
    for attempt in range(max_retries):
        try:
            async with httpx.AsyncClient(timeout=60.0) as client_http:
                resp = await client_http.post(url, headers=headers, json=payload)
            
            # 429 Rate Limit β€” wait and retry
            if resp.status_code == 429:
                wait_time = 10 * (attempt + 1)
                logger.warning(f"[Gemini] Rate limit (429). Retrying in {wait_time}s... (Attempt {attempt+1}/{max_retries})")
                await asyncio.sleep(wait_time)
                continue

            # 503 Service Unavailable β€” model under high load, use exponential backoff
            if resp.status_code == 503:
                wait_time = min(5 * (2 ** attempt), 60)  # 5s, 10s, 20s, 40s, 60s
                logger.warning(f"[Gemini] Server overloaded (503). Retrying in {wait_time}s... (Attempt {attempt+1}/{max_retries})")
                await asyncio.sleep(wait_time)
                continue
                
            if resp.status_code != 200:
                logger.error(f"[Gemini] HTTP Error {resp.status_code}: {resp.text[:200]}")
                resp.raise_for_status()
                
            data = resp.json()
            
            # Extract text from response
            try:
                content = data['candidates'][0]['content']['parts'][0]['text'].strip()
            except (KeyError, IndexError) as parse_err:
                logger.error(f"[Gemini] Response parse error: {parse_err}. Response data: {data}")
                last_error = Exception(f"Failed to parse Gemini response: {data}")
                await asyncio.sleep(2)
                continue
                
            if not content:
                last_error = Exception("Gemini returned empty response")
                await asyncio.sleep(2)
                continue
            
            logger.info("[Gemini] βœ… Content generated successfully")
            return _clean_markdown(content)
            
        except Exception as e:
            last_error = e
            logger.error(f"[Gemini] API error on attempt {attempt+1}: {e}")
            await asyncio.sleep(3)
            
    raise Exception(f"[Gemini] Failed after {max_retries} attempts: {last_error}")


def _channel_subjects(channel_key: str) -> list:
    """Return subjects active for this channel on today's rotation, filtered by syllabus availability."""
    channel_cfg = config_manager.channels.get(channel_key, {})
    exam_focus = channel_cfg.get("exam_focus", ["JEE Main"])
    
    # Get all subjects available in the syllabus for this exam
    all_syllabus_subjects = set()
    for focus in exam_focus:
        all_syllabus_subjects.update(syllabus_manager.get_all_subjects(focus))
        
    ch_subjects  = set(channel_cfg.get("subjects", list(all_syllabus_subjects)))
    day_subjects  = set(SUBJECT_ROTATION.get(_today(), list(all_syllabus_subjects)))
    active = list(ch_subjects & day_subjects)
    return active if active else list(ch_subjects)


def _pick(channel_key: str, content_type: str) -> tuple:
    """Pick a non-repeating (subject, chapter) pair for this channel + content type."""
    subjects = _channel_subjects(channel_key)
    subject  = random.choice(subjects)
    chapter  = pick_fresh_chapter(channel_key, content_type, subject)
    return subject, chapter


def _footer(channel_key: str, tag_key: str) -> str:
    cfg     = config_manager.channels.get(channel_key, {})
    hashtag = cfg.get("hashtags", {}).get(tag_key, "")
    
    footer_text = (
        "─────────────────────\n"
        "πŸ‘ React  |  πŸ“Œ Save  |  πŸ“’ Share\n"
        "πŸš€ @xcrazylearners"
    )
    
    if hashtag:
        return f"\n\n{hashtag}\n{footer_text}"
    else:
        return f"\n\n{footer_text}"


def _exam(channel_key: str) -> str:
    exams = config_manager.channels.get(channel_key, {}).get("exam_focus", ["JEE Main"])
    return random.choice(exams)

def _difficulty_context(channel_key: str) -> str:
    """Returns a difficulty instruction based on the channel's target exams."""
    cfg = config_manager.channels.get(channel_key, {})
    exams = cfg.get("exam_focus", [])
    
    # Class 9/10 focus
    if any(ex in ["Class 9", "Class 10", "NTSE", "Foundation"] for ex in exams):
        return "Difficulty: Foundation/School Level. Focus on basic concepts, definitions, and clear logic. Avoid extremely complex calculus or advanced topics."
    
    # JEE Advanced focus
    if "JEE Advanced" in exams:
        return "Difficulty: Advanced/Hard. Use multi-concept problems, challenging numericals, and tricky logic. Focus on deep understanding."
    
    # JEE Main / NEET focus (default for competitive)
    return "Difficulty: Competitive (JEE Main/NEET level). Focus on accuracy, speed-based patterns, and standard competitive concepts."


# ─────────────────────────────────────────────
#  1. PYQ QUESTION (QUIZ MODE)
# ─────────────────────────────────────────────

import html

def _parse_quiz(text: str) -> dict:
    """Extracts quiz components from the AI-generated text."""
    try:
        import html
        text = html.unescape(text)
        
        # Question: everything between QUESTION: and (A)
        q_match = re.search(r'❓\s*\*?QUESTION:?\*?(.*?)(?=\([A-D]\)|\*\(A\))', text, re.DOTALL | re.IGNORECASE)
        if not q_match:
            q_match = re.search(r'QUESTION:?(.*?)(?=\([A-D]\)|\*\(A\))', text, re.DOTALL | re.IGNORECASE)
        
        question = q_match.group(1).strip() if q_match else ""
        question = re.sub(r'[*_~`]', '', question)  # Remove markdown formatting
        if len(question) > 297:
            question = question[:297] + "..."

        # Options
        options = []
        for label in ["(A)", "(B)", "(C)", "(D)"]:
            escaped_label = label.replace('(', r'\(').replace(')', r'\)')
            next_label = r'\([B-D]\)' if label != "(D)" else r'(?:βœ…|ANSWER|πŸ’‘)'
            pattern = r'(?:\*?)?' + escaped_label + r'(?:\*?)?(.*?)(?=(?:\*?)?' + next_label + ')'
            opt_match = re.search(pattern, text, re.DOTALL | re.IGNORECASE)
            if opt_match:
                opt_text = opt_match.group(1).strip()
                opt_text = re.sub(r'[*_~`]', '', opt_text)  # Remove markdown formatting
                options.append(opt_text[:100])
        
        # Deduplicate options
        unique_opts = []
        for o in options:
            while o in unique_opts:
                o += " "
            unique_opts.append(o)
        options = unique_opts

        if len(options) < 2:
            return None
            
        # Correct Answer
        ans_match = re.search(r'ANSWER:\s*\*?\(([A-D])\)', text, re.IGNORECASE)
        if not ans_match:
            ans_match = re.search(r'ANSWER:\s*\*?([A-D])\b', text, re.IGNORECASE)
        
        correct_letter = ans_match.group(1).upper() if ans_match else "A"
        correct_index = {"A": 0, "B": 1, "C": 2, "D": 3}.get(correct_letter, 0)
        correct_index = correct_index % len(options)
        
        # Explanation
        exp_match = re.search(r'πŸ’‘\s*\*?EXPLANATION:?\*?(.*?)(?=🎯|$)', text, re.DOTALL | re.IGNORECASE)
        if not exp_match:
            exp_match = re.search(r'EXPLANATION:?(.*?)(?=🎯|$)', text, re.DOTALL | re.IGNORECASE)
            
        explanation = exp_match.group(1).strip() if exp_match else ""
        explanation = re.sub(r'[*_~`]', '', explanation)  # Remove markdown formatting
        if len(explanation) > 197:
            explanation = explanation[:197] + "..."
            
        return {
            "question": question,
            "options": options,
            "correct_index": correct_index,
            "explanation": explanation,
            "full_text": text
        }
    except Exception as e:
        logger.error(f"Quiz parsing failed: {e}")
        return None


async def generate_pyq_question(channel_key: str) -> dict:
    subject, chapter = _pick(channel_key, "pyq_question")
    exam  = _exam(channel_key)
    year  = random.randint(2015, 2023)

    template = template_manager.get_template("pyq_question")
    diff_text = _difficulty_context(channel_key)
    prompt = template.format(
        exam=exam, year=year, chapter=chapter, 
        subject=subject.title()
    ) + f"\n\n{diff_text}"

    raw_text = await _call_llm(prompt)
    if not raw_text:
        return {"error": "⚠️ Content temporarily unavailable."}

    quiz_data = _parse_quiz(raw_text)
    if not quiz_data:
        # Fallback to plain text if parsing fails
        return {"text": raw_text + _footer(channel_key, "pyq")}

    # Return structured dict for the dispatcher
    return {
        "text": raw_text + _footer(channel_key, "pyq"),
        "quiz": quiz_data,
        "type": "quiz"
    }


# ─────────────────────────────────────────────
#  2. FORMULA SHEET
# ─────────────────────────────────────────────

async def generate_formula_sheet(channel_key: str) -> str:
    subject, chapter = _pick(channel_key, "formula_sheet")
    exam = _exam(channel_key)

    template = template_manager.get_template("formula_sheet")
    prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())

    text = await _call_llm(prompt)
    text = (text or "⚠️ Content temporarily unavailable.")
    
    # Archive for Weekly PDF
    if text != "⚠️ Content temporarily unavailable.":
        archive_weekly_post(channel_key, "formula_sheet", subject, chapter, text)
        
    return text + _footer(channel_key, "formula")


# ─────────────────────────────────────────────
#  3. SHORT NOTES
# ─────────────────────────────────────────────

async def generate_short_notes(channel_key: str) -> str:
    subject, chapter = _pick(channel_key, "short_notes")
    exam = _exam(channel_key)

    template = template_manager.get_template("short_notes")
    prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())

    text = await _call_llm(prompt)
    text = (text or "⚠️ Content temporarily unavailable.")
    
    # Archive for Weekly PDF
    if text != "⚠️ Content temporarily unavailable.":
        archive_weekly_post(channel_key, "short_notes", subject, chapter, text)
        
    return text + _footer(channel_key, "notes")


# ─────────────────────────────────────────────
#  4. MNEMONIC
# ─────────────────────────────────────────────

async def generate_mnemonic(channel_key: str) -> str:
    subject, chapter = _pick(channel_key, "mnemonic")

    template = template_manager.get_template("mnemonic")
    prompt = template.format(chapter=chapter, subject=subject.title())

    text = await _call_llm(prompt)
    return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mnemonic")


# ─────────────────────────────────────────────
#  5. CONCEPT RECAP
# ─────────────────────────────────────────────

async def generate_concept_recap(channel_key: str) -> str:
    subject, chapter = _pick(channel_key, "concept_recap")
    exam = _exam(channel_key)

    template = template_manager.get_template("concept_recap")
    prompt = template.format(exam=exam, chapter=chapter, subject=subject.title())

    text = await _call_llm(prompt)
    return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "recap")


# ─────────────────────────────────────────────
#  6. MOCK MCQ
# ─────────────────────────────────────────────

async def generate_mock_question(channel_key: str) -> str:
    subject, chapter = _pick(channel_key, "mock_question")
    exam = _exam(channel_key)

    template = template_manager.get_template("mock_question")
    diff_text = _difficulty_context(channel_key)
    prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"

    text = await _call_llm(prompt)
    return (text or "⚠️ Content temporarily unavailable.") + _footer(channel_key, "mock")


# ─────────────────────────────────────────────
#  7. MOTIVATIONAL
# ─────────────────────────────────────────────

async def generate_motivational(channel_key: str) -> str:
    exam = _exam(channel_key)

    # Pick a random subject and chapter to make the message specific
    subjects = _channel_subjects(channel_key)
    subject  = random.choice(subjects)
    chapter  = pick_fresh_chapter(channel_key, "motivational", subject)
    
    template = template_manager.get_template("motivational")
    prompt = template.format(exam=exam, subject=subject.title(), chapter=chapter)

    text = await _call_llm(prompt)
    cfg    = config_manager.channels.get(channel_key, {})
    footer = cfg.get("footer", "")
    return (text or "πŸŒ™ Rest well! See you tomorrow πŸ’ͺ") + (f"\n\n{footer}" if footer else "")


# ─────────────────────────────────────────────
#  8. MCQ POLL SESSION  (10 polls, chapter-wise)
# ─────────────────────────────────────────────

def _parse_mcq_json(text: str) -> list:
    """Extract and repair a JSON array of MCQ dicts from the Gemini response."""
    if not text: return []
    
    # 1. Basic Cleaning
    clean = text.strip()
    if clean.startswith("```"):
        clean = re.sub(r'^```(?:json)?\s*', '', clean, flags=re.MULTILINE)
        clean = re.sub(r'\s*```\s*$', '', clean, flags=re.MULTILINE).strip()

    # 2. Slice to array bounds if possible
    start = clean.find('[')
    if start == -1: return []
    
    # Try to find the last ']' - but if it's truncated, we might need to repair it
    end = clean.rfind(']')
    
    candidate = clean[start:]
    if end != -1:
        candidate = clean[start:end + 1]

    # 3. Progressive Repair Strategy
    try:
        return json.loads(candidate)
    except json.JSONDecodeError:
        # AI truncated mid-object? Let's try to fix it.
        # Strategy: Remove everything after the last valid "}," and add "]"
        last_comma = candidate.rfind('},')
        if last_comma != -1:
            try:
                return json.loads(candidate[:last_comma + 1] + "]")
            except: pass
        
        # Try finding the last "}" and closing the array
        last_brace = candidate.rfind('}')
        if last_brace != -1:
            try:
                return json.loads(candidate[:last_brace + 1] + "]")
            except: pass

    return []


async def generate_mcq_session(channel_key: str) -> dict:
    """Generate 10 MCQ Telegram quiz polls for a single chapter."""
    subject, chapter = _pick(channel_key, "mcq_session")
    exam = _exam(channel_key)

    template = template_manager.get_template("mcq_session")
    diff_text = _difficulty_context(channel_key)
    prompt = template.format(exam=exam, chapter=chapter, subject=subject.title()) + f"\n\n{diff_text}"

    raw = await _call_llm(prompt)
    if not raw:
        return {"error": "⚠️ MCQ Session content temporarily unavailable."}

    questions = _parse_mcq_json(raw)
    MIN_MCQ = 3  # Accept sessions with at least 3 valid questions
    if not questions or len(questions) < MIN_MCQ:
        logger.warning(f"MCQ session got only {len(questions)} questions (need {MIN_MCQ}) β€” retrying once")
        # --- One automatic retry before giving up ---
        raw2 = await _call_llm(prompt)
        if raw2:
            questions = _parse_mcq_json(raw2)
        if not questions or len(questions) < MIN_MCQ:
            logger.error(f"MCQ session still only {len(questions)} questions after retry β€” giving up")
            return {"error": "⚠️ Could not generate enough MCQs right now. Please retry."}

    # Clamp to exactly 10
    questions = questions[:10]

    # Sanitise each question for Telegram limits
    clean = []
    import html
    for q in questions:
        raw_opts = q.get("options", [])
        if not isinstance(raw_opts, list): continue
        
        # Convert to Markdown V2 and remove formatting symbols for clean display
        opts = [html.unescape(re.sub(r'[*_~`<>]', '', str(o)))[:100] for o in raw_opts]
        
        # Deduplicate
        unique_opts = []
        for o in opts:
            while o in unique_opts:
                o += " "
            unique_opts.append(o)
            
        if len(unique_opts) < 2:
            continue
            
        question_text = html.unescape(re.sub(r'[*_~`<>]', '', str(q.get("question", ""))))[:300]
        explanation = html.unescape(re.sub(r'[*_~`<>]', '', str(q.get("explanation", ""))))[:197]
        
        clean.append({
            "question":      question_text,
            "options":       unique_opts[:4],
            "correct_index": int(q.get("correct_index", 0)) % len(unique_opts[:4]),
            "explanation":   explanation,
        })

    return {
        "type":     "mcq_session",
        "subject":  subject,
        "chapter":  chapter,
        "exam":     exam,
        "questions": clean,
    }


# ─────────────────────────────────────────────
#  DISPATCHER
# ─────────────────────────────────────────────

CONTENT_GENERATORS = {
    "pyq_question":  generate_pyq_question,
    "formula_sheet": generate_formula_sheet,
    "short_notes":   generate_short_notes,
    "mnemonic":      generate_mnemonic,
    "concept_recap": generate_concept_recap,
    "mock_question": generate_mock_question,
    "motivational":  generate_motivational,
    "mcq_session":   generate_mcq_session,
}

CONTENT_LABELS = {
    "pyq_question":  "πŸ“… Daily PYQ Question",
    "formula_sheet": "πŸ“ Formula Sheet",
    "short_notes":   "πŸ“ Short Notes",
    "mnemonic":      "🧠 Memory Tricks",
    "concept_recap": "πŸŒ… Concept Recap",
    "mock_question": "🎯 Daily Mock",
    "motivational":  "πŸŒ™ Night Motivation",
    "mcq_session":   "πŸ§ͺ MCQ Poll Session",
}


async def generate_generic_ai_post(content_type: str, channel_key: str) -> dict:
    """Fallback generator for user-defined custom content types."""
    prompt_template = template_manager.data["templates"].get(content_type)
    if not prompt_template:
        return {"text": f"❌ No prompt template found for custom type: `{content_type}`"}

    subject, chapter = _pick(channel_key, content_type)
    exam = _exam(channel_key)
    year = datetime.now().year
    
    try:
        full_prompt = prompt_template.format(exam=exam, subject=subject, chapter=chapter, year=year)
    except KeyError as e:
        # Fallback if user uses a placeholder we don't have
        full_prompt = prompt_template
        logger.warning(f"Template for {content_type} has unknown placeholder {e}")

    text = await _call_llm(full_prompt)
    if not text:
        return {"error": "Gemini failed to generate text."}

    return {
        "text": _clean_markdown(text) + _footer(channel_key, content_type)
    }


async def generate_content(content_type: str, channel_key: str) -> str:
    gen = CONTENT_GENERATORS.get(content_type)
    if not gen:
        # Try generic generator for custom types
        return await generate_generic_ai_post(content_type, channel_key)
    return await gen(channel_key)