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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8065f3
 
 
b6e32c9
c8065f3
b6e32c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8065f3
 
 
 
 
b6e32c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8065f3
 
 
 
 
 
 
 
 
b6e32c9
c8065f3
b6e32c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
951d5c6
 
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
import logging
import asyncio
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends
from sqlalchemy.orm import Session
from datetime import datetime
from typing import Dict, Any

from api.auth import get_current_user_ws
from models import db_models
from core.database import get_db
from services.flashcard_service import flashcard_service
from services.quiz_service import quiz_service
from services.report_service import report_service
from services.mindmap_service import mindmap_service
from services.podcast_service import podcast_service
from services.s3_service import s3_service
from services.video_generator_service import video_generator_service
from services.slides_video_service import slides_video_service
from models.schemas import VideoSummaryGenerateRequest, ReportGenerateRequest, MindMapGenerateRequest

router = APIRouter(prefix="/ws", tags=["websockets"])
logger = logging.getLogger(__name__)


class ConnectionManager:
    """Manages WebSocket connections for parallel execution"""
    
    def __init__(self):
        self.active_connections: Dict[str, WebSocket] = {}
    
    async def connect(self, websocket: WebSocket, connection_id: str):
        await websocket.accept()
        self.active_connections[connection_id] = websocket
        logger.info(f"WebSocket connected: {connection_id}")
    
    def disconnect(self, connection_id: str):
        if connection_id in self.active_connections:
            del self.active_connections[connection_id]
            logger.info(f"WebSocket disconnected: {connection_id}")
    
    async def send_progress(self, connection_id: str, progress: int, status: str, message: str = ""):
        if connection_id in self.active_connections:
            try:
                await self.active_connections[connection_id].send_json({
                    "type": "progress",
                    "progress": progress,
                    "status": status,
                    "message": message
                })
            except Exception as e:
                logger.error(f"Error sending progress to {connection_id}: {e}")
    
    async def send_result(self, connection_id: str, data: Any):
        if connection_id in self.active_connections:
            try:
                await self.active_connections[connection_id].send_json({
                    "type": "result",
                    "status": "complete",
                    "progress": 100,
                    "data": data
                })
            except Exception as e:
                logger.error(f"Error sending result to {connection_id}: {e}")
    
    async def send_error(self, connection_id: str, error: str):
        if connection_id in self.active_connections:
            try:
                await self.active_connections[connection_id].send_json({
                    "type": "error",
                    "status": "error",
                    "message": error
                })
            except Exception as e:
                logger.error(f"Error sending error to {connection_id}: {e}")


manager = ConnectionManager()


@router.websocket("/generate")
async def unified_generate_ws(
    websocket: WebSocket,
    token: str,
    db: Session = Depends(get_db)):
    """
    Unified WebSocket gateway for all generation tasks.
    Client sends JSON: { "type": "podcast|flashcards|quiz|mindmap|report|video", "data": { ... } }
    """
    await websocket.accept()
    
    try:
        current_user = await get_current_user_ws(token, db)
        connection_id = f"user_{current_user.id}"
        manager.active_connections[connection_id] = websocket
        
        # Receive the task specification
        message = await websocket.receive_json()
        task_type = message.get("type")
        data = message.get("data", {})
        
        if not task_type:
            await manager.send_error(connection_id, "Missing 'type' in request")
            return

        await manager.send_progress(connection_id, 2, "processing", f"Initializing {task_type} task...")

        # --- ROUTING LOGIC ---
        
        if task_type == "podcast":
            await handle_podcast_task(connection_id, data, current_user, db)
        
        elif task_type == "video":
            await handle_video_task(connection_id, data, current_user, db)
            
        elif task_type == "report":
            await handle_report_task(connection_id, data, current_user, db)
            
        elif task_type == "mindmap":
            await handle_mindmap_task(connection_id, data, current_user, db)

        elif task_type == "flashcards":
            await handle_flashcards_task(connection_id, data, current_user, db)

        elif task_type == "quiz":
            await handle_quiz_task(connection_id, data, current_user, db)
            
        else:
            await manager.send_error(connection_id, f"Unsupported task type: {task_type}")

    except WebSocketDisconnect:
        logger.info(f"Client disconnected")
    except Exception as e:
        logger.error(f"Unified WebSocket error: {e}")
        try:
            await manager.send_error(connection_id, str(e))
        except: pass
    finally:
        if 'connection_id' in locals():
            manager.disconnect(connection_id)

async def handle_podcast_task(connection_id: str, data: Dict, current_user: db_models.User, db: Session):
    """Internal handler for podcast generation"""
    try:
        source_id = None
        if data.get("file_key"):
            source = db.query(db_models.Source).filter(
                db_models.Source.s3_key == data["file_key"],
                db_models.Source.user_id == current_user.id
            ).first()
            if not source:
                await manager.send_error(connection_id, "Not authorized to access this file")
                return
            source_id = source.id
        
        file_base = data.get("file_key").split('/')[-1].rsplit('.', 1)[0] if data.get("file_key") else None
        title = f"Podcast-{file_base}" if file_base else f"Podcast {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}"
        
        db_podcast = db_models.Podcast(
            title=title,
            user_id=current_user.id,
            source_id=source_id,
            status="processing"
        )
        db.add(db_podcast)
        db.commit()
        db.refresh(db_podcast)

        db_podcast.status = "processing"
        db.commit()

        analysis_report = ""
        if data.get("file_key"):
            await manager.send_progress(connection_id, 10, "processing", "Analyzing source file...")
            analysis_report = await podcast_service.analyze_pdf(
                file_key=data["file_key"],
                duration_minutes=data.get("duration_minutes", 10)
            )

        await manager.send_progress(connection_id, 15, "processing", "Generating podcast script...")
        script = await podcast_service.generate_script(
            user_prompt=data["user_prompt"],
            model=data.get("model", "gpt-4o"),
            duration_minutes=data.get("duration_minutes", 10),
            podcast_format=data.get("podcast_format", "conversational"),
            pdf_suggestions=analysis_report,
            file_key=data.get("file_key")
        )
        
        if not script: raise Exception("Failed to generate script")
        
        await manager.send_progress(connection_id, 45, "processing", "Generating audio...")
        audio_path = await podcast_service.generate_full_audio(
            script=script,
            tts_model=data.get("tts_model", "gemini-2.0-flash-exp"),
            spk1_voice=data.get("spk1_voice", "Puck"),
            spk2_voice=data.get("spk2_voice", "Charon"),
            temperature=data.get("temperature", 1.0),
            bgm_choice=data.get("bgm_choice", "No BGM")
        )
        
        if not audio_path: raise Exception("Failed to generate audio")
        
        await manager.send_progress(connection_id, 90, "processing", "Uploading to S3...")
        import os
        filename = os.path.basename(audio_path)
        s3_key = f"users/{current_user.id}/outputs/podcasts/{filename}"
        
        def upload_audio_sync():
            with open(audio_path, "rb") as f:
                content = f.read()
            import boto3
            from core.config import settings
            boto3.client('s3', 
                         aws_access_key_id=settings.AWS_ACCESS_KEY_ID, 
                         aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
                         region_name=settings.AWS_REGION).put_object(Bucket=settings.AWS_S3_BUCKET, Key=s3_key, Body=content)

        await asyncio.to_thread(upload_audio_sync)
        
        public_url = s3_service.get_public_url(s3_key)
        
        db_podcast.s3_key = s3_key
        db_podcast.s3_url = public_url
        db_podcast.script = script
        db_podcast.status = "completed"
        db.commit()
        
        if os.path.exists(audio_path): os.remove(audio_path)
        
        await manager.send_result(connection_id, {
            "id": db_podcast.id,
            "status": "completed",
            "message": "Podcast generated successfully",
            "public_url": public_url
        })
        
    except Exception as e:
        logger.error(f"Podcast task failed: {e}")
        if 'db_podcast' in locals():
            db_podcast.status = "failed"
            db_podcast.error_message = str(e)
            db.commit()
        await manager.send_error(connection_id, str(e))

async def handle_flashcards_task(connection_id: str, data: Dict, current_user: db_models.User, db: Session):
    """Internal handler for flashcard generation"""
    try:
        source_id = None
        source = None
        if data.get("file_key"):
            source = db.query(db_models.Source).filter(
                db_models.Source.s3_key == data["file_key"],
                db_models.Source.user_id == current_user.id
            ).first()
            if not source:
                await manager.send_error(connection_id, "Not authorized to access this file")
                return
            source_id = source.id
        
        # Create initial processing record
        file_base = data.get("file_key").split('/')[-1].rsplit('.', 1)[0] if data.get("file_key") else None
        
        if file_base:
            title = f"Flashcard-{file_base}"
        elif data.get("topic") and data.get("topic") != "string":
            title = data.get("topic")
        else:
            title = f"Flashcards {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}"

        db_set = db_models.FlashcardSet(
            title=title,
            difficulty=data.get("difficulty", "medium"),
            user_id=current_user.id,
            source_id=source_id,
            status="processing"
        )
        db.add(db_set)
        db.commit()
        db.refresh(db_set)
        
        await manager.send_progress(connection_id, 10, "processing", "Generating flashcards...")
        
        cards_data = await flashcard_service.generate_flashcards(
            file_key=data.get("file_key"),
            text_input=data.get("text_input"),
            difficulty=data.get("difficulty", "medium"),
            quantity=data.get("quantity", "standard"),
            topic=data.get("topic"),
            language=data.get("language", "English"),
            progress_callback=lambda p, m: asyncio.create_task(
                manager.send_progress(connection_id, 10 + int(p * 0.7), "processing", m)
            )
        )
        
        if not cards_data:
            raise Exception("AI returned empty flashcard data")
        
        await manager.send_progress(connection_id, 85, "processing", "Saving to database...")
        
        for item in cards_data:
            db_card = db_models.Flashcard(
                flashcard_set_id=db_set.id,
                question=item.get("question", ""),
                answer=item.get("answer", "")
            )
            db.add(db_card)
        
        db_set.status = "completed"
        db.commit()
        
        await manager.send_result(connection_id, {
            "id": db_set.id,
            "title": db_set.title,
            "flashcards_count": len(db_set.flashcards),
            "status": "completed"
        })
    except Exception as e:
        logger.error(f"Flashcard task failed: {e}")
        if 'db_set' in locals():
            db_set.status = "failed"
            db_set.error_message = str(e)
            db.commit()
        await manager.send_error(connection_id, str(e))

async def handle_quiz_task(connection_id: str, data: Dict, current_user: db_models.User, db: Session):
    """Internal handler for quiz generation"""
    try:
        source_id = None
        if data.get("file_key"):
            source = db.query(db_models.Source).filter(
                db_models.Source.s3_key == data["file_key"],
                db_models.Source.user_id == current_user.id
            ).first()
            if not source:
                await manager.send_error(connection_id, "Not authorized to access this file")
                return
            source_id = source.id
        
        # Create initial processing record
        file_base = data.get("file_key").split('/')[-1].rsplit('.', 1)[0] if data.get("file_key") else None
        
        if file_base:
            title = f"Quiz-{file_base}"
        elif data.get("topic") and data.get("topic") != "string":
            title = data.get("topic")
        else:
            title = f"Quiz {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}"

        db_set = db_models.QuizSet(
            title=title,
            difficulty=data.get("difficulty", "medium"),
            user_id=current_user.id,
            source_id=source_id,
            status="processing"
        )
        db.add(db_set)
        db.commit()
        db.refresh(db_set)

        await manager.send_progress(connection_id, 10, "processing", "Generating quiz...")
        
        quizzes_data = await quiz_service.generate_quiz(
            file_key=data.get("file_key"),
            text_input=data.get("text_input"),
            difficulty=data.get("difficulty", "medium"),
            topic=data.get("topic"),
            language=data.get("language", "English"),
            count_mode=data.get("count", "STANDARD"),
            progress_callback=lambda p, m: asyncio.create_task(
                manager.send_progress(connection_id, 10 + int(p * 0.7), "processing", m)
            )
        )
        
        if not quizzes_data:
            raise Exception("AI failed to generate quiz data")
        
        for item in quizzes_data:
            db_question = db_models.QuizQuestion(
                quiz_set_id=db_set.id,
                question=item.get("question", ""),
                choices=item.get("choices", {}),
                answer=str(item.get("answer", "1")),
                explanation=item.get("explanation", "")
            )
            db.add(db_question)
        
        db_set.status = "completed"
        db.commit()
        await manager.send_result(connection_id, {"id": db_set.id, "title": db_set.title, "status": "completed"})
    except Exception as e:
        logger.error(f"Quiz task failed: {e}")
        if 'db_set' in locals():
            db_set.status = "failed"
            db_set.error_message = str(e)
            db.commit()
        await manager.send_error(connection_id, str(e))

async def handle_video_task(connection_id: str, data: Dict, current_user: db_models.User, db: Session):
    """Internal handler for video summary generation"""
    try:
        source = db.query(db_models.Source).filter(
            db_models.Source.s3_key == data.get("file_key"),
            db_models.Source.user_id == current_user.id
        ).first()
        if not source:
            await manager.send_error(connection_id, "Not authorized to access this file")
            return

        file_base = data.get("file_key").split('/')[-1].rsplit('.', 1)[0] if data.get("file_key") else None
        title = f"Video Summary {file_base}" if file_base else f"Video Summary {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}"

        db_summary = db_models.VideoSummary(
            title=title,
            user_id=current_user.id,
            source_id=source.id,
            status="processing"
        )
        db.add(db_summary)
        db.commit()
        db.refresh(db_summary)

        await manager.send_progress(connection_id, 10, "processing", "Starting video generation...")

        if data.get("use_slides_transformation", True):
            result = await slides_video_service.generate_transformed_video_summary(
                file_key=data["file_key"],
                language=data.get("language", "Japanese"),
                voice_name=data.get("voice_name", "Kore"),
                custom_prompt=data.get("custom_prompt", "")
            )
        else:
            result = await video_generator_service.generate_video_summary(
                file_key=data["file_key"],
                language=data.get("language", "Japanese"),
                voice_name=data.get("voice_name", "Kore")
            )

        db_summary.title = result["title"]
        db_summary.s3_key = result["s3_key"]
        db_summary.s3_url = result["s3_url"]
        db_summary.status = "completed"
        db.commit()

        await manager.send_result(connection_id, {
            "type": "video",
            "id": db_summary.id,
            "status": "completed",
            "title": db_summary.title,
            "public_url": db_summary.s3_url
        })
    except Exception as e:
        logger.error(f"Video task failed: {e}")
        if 'db_summary' in locals():
            db_summary.status = "failed"
            db_summary.error_message = str(e)
            db.commit()
        await manager.send_error(connection_id, str(e))

async def handle_report_task(connection_id: str, data: Dict, current_user: db_models.User, db: Session):
    """Internal handler for report generation"""
    try:
        source_id = None
        if data.get("file_key"):
            source = db.query(db_models.Source).filter(
                db_models.Source.s3_key == data["file_key"],
                db_models.Source.user_id == current_user.id
            ).first()
            if not source:
                await manager.send_error(connection_id, "Not authorized to access this file")
                return
            source_id = source.id

        file_base = data.get("file_key").split('/')[-1].rsplit('.', 1)[0] if data.get("file_key") else None
        title = f"Report-{file_base}" if file_base else f"Report {data.get('format_key', 'custom')} {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}"

        db_report = db_models.Report(
            title=title,
            format_key=data.get("format_key", "custom"),
            user_id=current_user.id,
            source_id=source_id,
            status="processing"
        )
        db.add(db_report)
        db.commit()
        db.refresh(db_report)

        await manager.send_progress(connection_id, 15, "processing", "Generating report content...")

        content = await report_service.generate_report(
            file_key=data.get("file_key"),
            text_input=data.get("text_input"),
            format_key=data.get("format_key", "briefing_doc"),
            custom_prompt=data.get("custom_prompt"),
            language=data.get("language", "Japanese")
        )

        if not content:
            raise Exception("AI failed to generate report content")

        if not db_report.title or "Report-" not in db_report.title:
            title = content.split('\n')[0].replace('#', '').strip()
            if not title or len(title) < 3:
                title = f"Report {data.get('format_key')}"
            db_report.title = title
        db_report.content = content
        db_report.status = "completed"
        db.commit()

        await manager.send_result(connection_id, {
            "type": "report",
            "id": db_report.id,
            "status": "completed",
            "title": db_report.title
        })
    except Exception as e:
        logger.error(f"Report task failed: {e}")
        if 'db_report' in locals():
            db_report.status = "failed"
            db_report.error_message = str(e)
            db.commit()
        await manager.send_error(connection_id, str(e))

async def handle_mindmap_task(connection_id: str, data: Dict, current_user: db_models.User, db: Session):
    """Internal handler for mindmap generation"""
    try:
        source_id = None
        if data.get("file_key"):
            source = db.query(db_models.Source).filter(
                db_models.Source.s3_key == data["file_key"],
                db_models.Source.user_id == current_user.id
            ).first()
            if not source:
                await manager.send_error(connection_id, "Not authorized to access this file")
                return
            source_id = source.id

        file_base = data.get("file_key").split('/')[-1].rsplit('.', 1)[0] if data.get("file_key") else None
        
        if file_base:
            title = f"Mind Map-{file_base}"
        elif data.get("title") and data.get("title") != "string":
            title = data.get("title")
        else:
            title = f"Mind Map {datetime.utcnow().strftime('%Y-%m-%d %H:%M')}"

        db_mindmap = db_models.MindMap(
            title=title,
            user_id=current_user.id,
            source_id=source_id,
            status="processing"
        )
        db.add(db_mindmap)
        db.commit()
        db.refresh(db_mindmap)

        await manager.send_progress(connection_id, 20, "processing", "Generating mind map visualization...")

        mermaid_code = await mindmap_service.generate_mindmap(
            file_key=data.get("file_key"),
            text_input=data.get("text_input")
        )

        if not mermaid_code:
            raise Exception("AI failed to generate mind map code")

        db_mindmap.mermaid_code = mermaid_code
        db_mindmap.status = "completed"
        db.commit()

        await manager.send_result(connection_id, {
            "type": "mindmap",
            "id": db_mindmap.id,
            "status": "completed",
            "title": db_mindmap.title
        })
    except Exception as e:
        logger.error(f"Mindmap task failed: {e}")
        if 'db_mindmap' in locals():
            db_mindmap.status = "failed"
            db_mindmap.error_message = str(e)
            db.commit()
        await manager.send_error(connection_id, str(e))