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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
import io
import re
import os
import sys
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Header
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from pptx import Presentation
from pptx.util import Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN

# Firebase Cloud Functions Imports
from firebase_functions import https_fn
from firebase_admin import initialize_app

# Initialize Firebase Admin
try:
    initialize_app()
except Exception:
    pass

# Initialize FastAPI app
app = FastAPI(title="PPTX Reveal Generator API")

# Enable CORS restricted only to your production domain and local test servers
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "https://bytebard-27064.web.app",
        "https://bytebard-27064.firebaseapp.com",
        "http://localhost:3000",
        "http://localhost:8000"
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


def clean_text(text):
    if not text:
        return ""
    return " ".join(text.strip().split())

def parse_question_block(text, slide_num):
    text = clean_text(text)
    
    # Extract Answer
    ans_match = re.search(r"Answer\s*:\s*([A-D])", text, re.IGNORECASE)
    if not ans_match:
        ans_match = re.search(r"Answer\s+([A-D])", text, re.IGNORECASE)
        
    if ans_match:
        answer = ans_match.group(1).upper()
        content = text[:ans_match.start()].strip()
    else:
        answer = None
        content = text
        
    # Extract options A, B, C, D
    opt_b = re.search(r"\bB\s*\)", content) or re.search(r"\bB\s*\.", content)
    opt_c = re.search(r"\bC\s*\)", content) or re.search(r"\bC\s*\.", content)
    opt_d = re.search(r"\bD\s*\)", content) or re.search(r"\bD\s*\.", content)
    
    if opt_b and opt_c and opt_d:
        opt_d_text = content[opt_d.end():].strip()
        opt_c_text = content[opt_c.end():opt_d.start()].strip()
        opt_b_text = content[opt_b.end():opt_c.start()].strip()
        
        opt_a = re.search(r"\bA\s*\)", content[:opt_b.start()]) or re.search(r"\bA\s*\.", content[:opt_b.start()])
        if opt_a:
            opt_a_text = content[opt_a.end():opt_b.start()].strip()
            q_text = content[:opt_a.start()].strip()
        else:
            q_part = content[:opt_b.start()].strip()
            q_split = re.search(r"\?\s*", q_part) or re.search(r"\:\s*", q_part)
            if q_split:
                q_text = q_part[:q_split.end()].strip()
                opt_a_text = q_part[q_split.end():].strip()
            else:
                q_text = q_part
                opt_a_text = ""
    else:
        q_text = content
        opt_a_text, opt_b_text, opt_c_text, opt_d_text = "", "", "", ""
        
    q_num_match = re.match(r"^(\d+)\s*[\.\-]?\s*", q_text)
    if q_num_match:
        q_num = int(q_num_match.group(1))
        q_text = q_text[q_num_match.end():].strip()
    else:
        q_num = None
        
    def clean_opt(opt):
        opt = opt.strip()
        if opt.endswith(",") or opt.endswith(";"):
            opt = opt[:-1].strip()
        return opt
        
    return {
        "q_num": q_num,
        "question": q_text,
        "A": clean_opt(opt_a_text),
        "B": clean_opt(opt_b_text),
        "C": clean_opt(opt_c_text),
        "D": clean_opt(opt_d_text),
        "answer": answer,
        "original_slide": slide_num
    }

def hex_to_rgb(hex_str):
    hex_str = hex_str.lstrip('#')
    return RGBColor(*(int(hex_str[i:i+2], 16) for i in (0, 2, 4)))

def build_question_slide(prs, q, is_reveal_slide, font_cat, font_q, font_ans, font_opt, alignment, color_tag, color_q, color_ans, color_opt, color_muted, total_questions):
    blank_layout = prs.slide_layouts[6] # Blank
    slide = prs.slides.add_slide(blank_layout)
    
    slide_width = prs.slide_width
    slide_height = prs.slide_height
    
    # 10% side margins, 10% top/bottom margins
    left = int(slide_width * 0.1)
    top = int(slide_height * 0.1)
    width = int(slide_width * 0.8)
    height = int(slide_height * 0.8)
    
    textbox = slide.shapes.add_textbox(left, top, width, height)
    tf = textbox.text_frame
    tf.word_wrap = True
    tf.margin_left = tf.margin_right = tf.margin_top = tf.margin_bottom = 0
    
    # Alignment mapping
    align_map = {
        "left": PP_ALIGN.LEFT,
        "center": PP_ALIGN.CENTER,
        "right": PP_ALIGN.RIGHT
    }
    selected_alignment = align_map.get(alignment.lower(), PP_ALIGN.CENTER)
    
    # A) Category Tag
    p_cat = tf.paragraphs[0]
    p_cat.text = f"SECTION: {q['category'].upper()}"
    p_cat.font.size = Pt(font_cat)
    p_cat.font.bold = True
    p_cat.font.color.rgb = hex_to_rgb(color_tag)
    p_cat.alignment = selected_alignment
    p_cat.space_after = Pt(24)
    
    # B) Question Text
    p_q = tf.add_paragraph()
    p_q.text = f"{q['q_num']}. {q['question']}"
    p_q.font.size = Pt(font_q)
    p_q.font.bold = True
    p_q.font.color.rgb = hex_to_rgb(color_q)
    p_q.alignment = selected_alignment
    p_q.space_after = Pt(36)
    
    # C) Options (A, B, C, D)
    for option_letter in ['A', 'B', 'C', 'D']:
        p_opt = tf.add_paragraph()
        option_text = q[option_letter]
        p_opt.alignment = selected_alignment
        
        is_correct = is_reveal_slide and option_letter == q['answer']
        
        if is_correct:
            p_opt.text = f"[✓] {option_letter}) {option_text}"
            p_opt.font.size = Pt(font_ans)
            p_opt.font.bold = True
            p_opt.font.color.rgb = hex_to_rgb(color_ans)
        else:
            p_opt.text = f"{option_letter}) {option_text}"
            p_opt.font.size = Pt(font_opt)
            p_opt.font.bold = False
            if is_reveal_slide:
                p_opt.font.color.rgb = hex_to_rgb(color_muted)
            else:
                p_opt.font.color.rgb = hex_to_rgb(color_opt)
                
        p_opt.space_after = Pt(16)
        
    # D) Bottom progress tracker
    tracker_left = int(slide_width * 0.39)
    tracker_top = int(slide_height * 0.9)
    tracker_width = int(slide_width * 0.22)
    tracker_height = int(slide_height * 0.05)
    
    tracker_textbox = slide.shapes.add_textbox(tracker_left, tracker_top, tracker_width, tracker_height)
    tf_track = tracker_textbox.text_frame
    p_track = tf_track.paragraphs[0]
    p_track.text = f"Question {q['q_num']} of {total_questions}"
    p_track.alignment = PP_ALIGN.CENTER
    p_track.font.size = Pt(20)
    p_track.font.color.rgb = hex_to_rgb("#64748b")

@app.post("/api/generate-from-combined")
async def generate_from_combined(
    file: UploadFile = File(...),
    font_cat: int = Form(32),
    font_q: int = Form(48),
    font_ans: int = Form(40),
    font_opt: int = Form(36),
    alignment: str = Form("center"),
    color_tag: str = Form("#0284c7"),
    color_q: str = Form("#0f172a"),
    color_ans: str = Form("#15803d"),
    color_opt: str = Form("#334155"),
    color_muted: str = Form("#94a3b8"),
    x_api_key: str = Header(None)
):
    # Verify secure API key
    if x_api_key != "bytebard-secure-token-pptx-987":
        raise HTTPException(status_code=401, detail="Unauthorized request: Invalid or missing API key.")
        
    try:
        # Load the uploaded file bytes
        file_bytes = await file.read()

        prs = Presentation(io.BytesIO(file_bytes))
        
        # Section markers matching slide indices
        category_markers = {
            9: "Methods of Teaching",
            45: "Types of Tests and Tools for Evaluation",
            54: "Error Analysis and Remedial Teaching"
        }
        
        current_category = "SLA and Language Basics"
        questions = []
        
        # Parse Slides 2 to 60 (indices 1 to 59)
        for idx in range(1, 60):
            if idx >= len(prs.slides):
                break
            slide = prs.slides[idx]
            slide_num = idx + 1
            
            if slide_num - 1 in category_markers:
                current_category = category_markers[slide_num - 1]
                
            paras = []
            for shape in slide.shapes:
                if shape.has_text_frame:
                    for p in shape.text_frame.paragraphs:
                        txt = clean_text(p.text)
                        if txt and txt not in ["Methods of Teaching", "Types of Tests and Tools for Evaluation", "Error Analysis and Remedial Teaching"]:
                            paras.append(txt)
                            
            blocks = []
            current_block = []
            for p in paras:
                starts_with_num = re.match(r"^(\d+)\s*[\.\-]\s+", p)
                if starts_with_num and current_block:
                    blocks.append(" ".join(current_block))
                    current_block = [p]
                else:
                    current_block.append(p)
            if current_block:
                blocks.append(" ".join(current_block))
                
            for block in blocks:
                q_data = parse_question_block(block, slide_num)
                q_data["category"] = current_category
                questions.append(q_data)
                
        for i, q in enumerate(questions):
            if q["q_num"] is None:
                q["q_num"] = i + 1
                
        total_questions = len(questions)
        
        # Build reveal slide pairs at the end of the presentation
        for q in questions:
            build_question_slide(prs, q, False, font_cat, font_q, font_ans, font_opt, alignment, color_tag, color_q, color_ans, color_opt, color_muted, total_questions)
            build_question_slide(prs, q, True, font_cat, font_q, font_ans, font_opt, alignment, color_tag, color_q, color_ans, color_opt, color_muted, total_questions)
            
        # Safely delete intermediate slides (Slides index 1 to 59)
        # Slides count must be >= 61
        original_count = min(61, len(prs.slides))
        to_delete = original_count - 2
        for _ in range(to_delete):
            del prs.slides._sldIdLst[1]
            
        # Move the thank-you slide (which is currently second at index 1) to the end
        sldIdLst = prs.slides._sldIdLst
        if len(sldIdLst) > 1:
            end_slide_element = sldIdLst[1]
            sldIdLst.remove(end_slide_element)
            sldIdLst.append(end_slide_element)
            
        # Save output presentation to file buffer
        output_buffer = io.BytesIO()
        prs.save(output_buffer)
        output_buffer.seek(0)
        
        return StreamingResponse(
            output_buffer,
            media_type="application/vnd.openxmlformats-officedocument.presentationml.presentation",
            headers={"Content-Disposition": f"attachment; filename=polished_reveal_deck.pptx"}
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/generate-from-template")
async def generate_from_template(
    template: UploadFile = File(...),
    questions_data: str = Form(...), # Paste Q&A text raw block
    font_cat: int = Form(32),
    font_q: int = Form(48),
    font_ans: int = Form(40),
    font_opt: int = Form(36),
    alignment: str = Form("center"),
    color_tag: str = Form("#0284c7"),
    color_q: str = Form("#0f172a"),
    color_ans: str = Form("#15803d"),
    color_opt: str = Form("#334155"),
    color_muted: str = Form("#94a3b8"),
    x_api_key: str = Header(None)
):
    # Verify secure API key
    if x_api_key != "bytebard-secure-token-pptx-987":
        raise HTTPException(status_code=401, detail="Unauthorized request: Invalid or missing API key.")
        
    try:
        # Load the blank template presentation
        template_bytes = await template.read()
        prs = Presentation(io.BytesIO(template_bytes))

        
        # Parse raw pasted questions_data
        # Format assumed: questions separated by newlines, with A), B), C), D) options and Answer: X
        raw_blocks = re.split(r"\n\s*(?=\d+\.|\bQuestion\b|\bQ\d+:)", questions_data.strip())
        if len(raw_blocks) <= 1:
            # Try splitting by double newline
            raw_blocks = [b.strip() for b in questions_data.strip().split("\n\n") if b.strip()]
            
        questions = []
        current_category = "General Knowledge"
        
        for i, block in enumerate(raw_blocks):
            # Detect category switches if any
            cat_match = re.search(r"Category\s*:\s*([^\n]+)", block, re.IGNORECASE)
            if cat_match:
                current_category = cat_match.group(1).strip()
                block = block.replace(cat_match.group(0), "").strip()
                
            q_data = parse_question_block(block, i + 1)
            q_data["category"] = current_category
            if q_data["question"]:
                questions.append(q_data)
                
        for i, q in enumerate(questions):
            if q["q_num"] is None:
                q["q_num"] = i + 1
                
        total_questions = len(questions)
        
        if total_questions == 0:
            raise HTTPException(status_code=400, detail="No valid questions could be parsed from input text.")
            
        # Build slide pairs
        for q in questions:
            build_question_slide(prs, q, False, font_cat, font_q, font_ans, font_opt, alignment, color_tag, color_q, color_ans, color_opt, color_muted, total_questions)
            build_question_slide(prs, q, True, font_cat, font_q, font_ans, font_opt, alignment, color_tag, color_q, color_ans, color_opt, color_muted, total_questions)
            
        # If the template had standard intermediate slides, delete them keeping first (index 0) and last slides
        if len(prs.slides) > (total_questions * 2) + 2:
            original_count = len(prs.slides) - (total_questions * 2)
            to_delete = original_count - 2
            for _ in range(to_delete):
                del prs.slides._sldIdLst[1]
                
            # Move last original slide to very end
            sldIdLst = prs.slides._sldIdLst
            end_slide_element = sldIdLst[1]
            sldIdLst.remove(end_slide_element)
            sldIdLst.append(end_slide_element)
            
        # Save output presentation
        output_buffer = io.BytesIO()
        prs.save(output_buffer)
        output_buffer.seek(0)
        
        return StreamingResponse(
            output_buffer,
            media_type="application/vnd.openxmlformats-officedocument.presentationml.presentation",
            headers={"Content-Disposition": f"attachment; filename=compiled_reveal_deck.pptx"}
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# FastAPI local testing server runner
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

# Firebase Cloud Functions Entrypoint Adaptor
@https_fn.on_request()
def api_endpoint(req: https_fn.Request) -> https_fn.Response:
    from fastapi.testclient import TestClient
    client = TestClient(app)
    
    # Map raw Flask-like request metadata to FastAPI's TestClient
    method = req.method
    path = req.path
    if req.query_string:
        path = f"{path}?{req.query_string.decode('utf-8')}"
        
    headers = dict(req.headers)
    
    # Forward the request using TestClient
    response = client.request(
        method=method,
        url=path,
        headers=headers,
        content=req.get_data(),
        cookies=req.cookies,
        follow_redirects=False
    )
    
    # Prepare and return the serverless response
    return https_fn.Response(
        response=response.content,
        status=response.status_code,
        headers=dict(response.headers)
    )