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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
FastAPI main application with SSE streaming support.
"""
import os
import uuid
import base64
import json
from typing import Optional, List
from contextlib import asynccontextmanager

from dotenv import load_dotenv

load_dotenv()

from fastapi import FastAPI, HTTPException, UploadFile, File, Form, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from sqlalchemy import select, delete
from sqlalchemy.ext.asyncio import AsyncSession
from langchain_core.messages import HumanMessage, AIMessage

from backend.database.models import init_db, AsyncSessionLocal, Conversation, Message
from backend.agent.graph import agent_graph
from backend.agent.state import AgentState
from backend.utils.rate_limit import rate_limiter
from backend.utils.tracing import setup_langsmith, create_run_config, get_tracing_status


@asynccontextmanager
async def lifespan(app: FastAPI):
    """Initialize database and LangSmith on startup."""
    await init_db()
    setup_langsmith()  # Initialize LangSmith tracing
    yield


app = FastAPI(
    title="Algebra Chatbot API",
    description="AI-powered algebra tutor using LangGraph",
    version="1.0.0",
    lifespan=lifespan,
)

# CORS for frontend
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
    expose_headers=["*"],  # Critical for frontend to read X-Session-Id
)


# Pydantic models
class ChatRequest(BaseModel):
    message: str
    session_id: Optional[str] = None


class UpdateConversationRequest(BaseModel):
    title: str


class ConversationResponse(BaseModel):
    id: str
    title: Optional[str]
    created_at: str
    updated_at: str


class MessageResponse(BaseModel):
    id: str
    role: str
    content: str
    image_data: Optional[str] = None  # Add this field
    created_at: str


class SearchResult(BaseModel):
    type: str  # 'conversation' or 'message'
    id: str
    title: Optional[str]  # Conversation title
    content: Optional[str] = None # Message content or snippet
    conversation_id: str
    created_at: str


# Database dependency
async def get_db():
    async with AsyncSessionLocal() as session:
        yield session


# API Routes
@app.get("/api/health")
async def health_check():
    """Health check endpoint."""
    return {"status": "healthy", "service": "algebra-chatbot"}


@app.get("/api/conversations", response_model=list[ConversationResponse])
async def list_conversations(db: AsyncSession = Depends(get_db)):
    """List all conversations."""
    result = await db.execute(
        select(Conversation).order_by(Conversation.updated_at.desc())
    )
    conversations = result.scalars().all()
    return [
        ConversationResponse(
            id=c.id,
            title=c.title,
            created_at=c.created_at.isoformat(),
            updated_at=c.updated_at.isoformat(),
        )
        for c in conversations
    ]


@app.post("/api/conversations", response_model=ConversationResponse)
async def create_conversation(db: AsyncSession = Depends(get_db)):
    """Create a new conversation."""
    conversation = Conversation()
    db.add(conversation)
    await db.commit()
    await db.refresh(conversation)
    return ConversationResponse(
        id=conversation.id,
        title=conversation.title,
        created_at=conversation.created_at.isoformat(),
        updated_at=conversation.updated_at.isoformat(),
    )


@app.delete("/api/conversations/{conversation_id}")
async def delete_conversation(conversation_id: str, db: AsyncSession = Depends(get_db)):
    """Delete a conversation and reset its memory tracker."""
    # Reset memory tracker for this session
    from backend.utils.memory import memory_tracker
    memory_tracker.reset_usage(conversation_id)
    
    await db.execute(
        delete(Conversation).where(Conversation.id == conversation_id)
    )
    await db.commit()
    return {"status": "deleted"}


@app.patch("/api/conversations/{conversation_id}", response_model=ConversationResponse)
async def update_conversation(
    conversation_id: str, 
    request: UpdateConversationRequest, 
    db: AsyncSession = Depends(get_db)
):
    """Update a conversation title."""
    result = await db.execute(
        select(Conversation).where(Conversation.id == conversation_id)
    )
    conversation = result.scalar_one_or_none()
    if not conversation:
        raise HTTPException(status_code=404, detail="Conversation not found")
    
    conversation.title = request.title
    await db.commit()
    await db.refresh(conversation)
    
    return ConversationResponse(
        id=conversation.id,
        title=conversation.title,
        created_at=conversation.created_at.isoformat(),
        updated_at=conversation.updated_at.isoformat(),
    )


@app.get("/api/conversations/{conversation_id}/messages", response_model=list[MessageResponse])
async def get_messages(conversation_id: str, db: AsyncSession = Depends(get_db)):
    """Get all messages in a conversation."""
    result = await db.execute(
        select(Message)
        .where(Message.conversation_id == conversation_id)
        .order_by(Message.created_at)
    )
    messages = result.scalars().all()
    return [
        MessageResponse(
            id=m.id,
            role=m.role,
            content=m.content,
            image_data=m.image_data,  # Populate this field
            created_at=m.created_at.isoformat(),
        )
        for m in messages
    ]


@app.get("/api/search", response_model=list[SearchResult])
async def search(q: str, db: AsyncSession = Depends(get_db)):
    """
    Search conversations and messages.
    Query: q (string)
    """
    if not q or not q.strip():
        return []

    query = f"%{q.strip()}%"
    results = []

    # 1. Search Conversations
    conv_result = await db.execute(
        select(Conversation)
        .where(Conversation.title.ilike(query))
        .order_by(Conversation.updated_at.desc())
        .limit(10)
    )
    conversations = conv_result.scalars().all()
    for c in conversations:
        results.append(SearchResult(
            type="conversation",
            id=c.id,
            title=c.title,
            content=None,
            conversation_id=c.id,
            created_at=c.created_at.isoformat()
        ))

    # 2. Search Messages
    msg_result = await db.execute(
        select(Message, Conversation.title)
        .join(Conversation)
        .where(Message.content.ilike(query))
        .order_by(Message.created_at.desc())
        .limit(20)
    )
    messages = msg_result.all() # returns (Message, title) tuples
    
    for msg, title in messages:
        # Avoid duplicates if conversation is already found? 
        # Actually showing specific message matches is good even if conversation matches.
        
        # Smarter snippet generation to ensure the match is visible
        content = msg.content
        idx = content.lower().find(q.lower())
        if idx != -1:
            # If the match is beyond the first 40 chars, center it
            if idx > 40:
                start = max(0, idx - 40)
                end = min(len(content), idx + 60)
                content = "..." + content[start:end] + ("..." if end < len(msg.content) else "")
            elif len(content) > 100: # If match is found within first 40 chars, but content is still long
                content = content[:100] + "..."
        elif len(content) > 100: # If no match is found, just truncate if long
            content = content[:100] + "..."

        results.append(SearchResult(
             type="message",
             id=msg.id,
             title=title,
             content=content,
             conversation_id=msg.conversation_id,
             created_at=msg.created_at.isoformat()
        ))

    # Sort combined results by date (newest first)
    results.sort(key=lambda x: x.created_at, reverse=True)
    
    return results


@app.get("/api/conversations/{conversation_id}/memory")
async def get_session_memory(conversation_id: str):
    """Get memory usage status for a session."""
    from backend.utils.memory import memory_tracker, KIMI_K2_CONTEXT_LENGTH
    
    status = memory_tracker.check_status(conversation_id)
    return {
        "session_id": status.session_id,
        "used_tokens": status.used_tokens,
        "max_tokens": status.max_tokens,
        "percentage": round(status.percentage, 2),
        "status": status.status,
        "message": status.message,
        "remaining_tokens": memory_tracker.get_remaining_tokens(conversation_id),
    }


@app.post("/api/chat")
async def chat(
    message: Optional[str] = Form(None),  # Optional - can send image only
    session_id: Optional[str] = Form(None),
    images: List[UploadFile] = File([]),  # Support multiple images (max 5)
    db: AsyncSession = Depends(get_db),
):
    """
    Chat endpoint with streaming response.
    Supports text, images (up to 5), or both.
    """
    # Validate: need at least message or image
    if not message and len(images) == 0:
        raise HTTPException(status_code=400, detail="Phải gửi ít nhất tin nhắn hoặc hình ảnh")
    
    # Limit to 5 images
    if len(images) > 5:
        raise HTTPException(status_code=400, detail="Tối đa 5 ảnh mỗi tin nhắn")
    
    # Default message for image-only queries
    if not message:
        message = "Giải bài toán trong ảnh này"
    
    # Get or create session
    if not session_id:
        conversation = Conversation(title=message[:50] if message else "Ảnh")
        db.add(conversation)
        await db.commit()
        await db.refresh(conversation)
        session_id = conversation.id
    else:
        result = await db.execute(
            select(Conversation).where(Conversation.id == session_id)
        )
        conversation = result.scalar_one_or_none()
        if not conversation:
            raise HTTPException(status_code=404, detail="Conversation not found")
    
    # Process all images into list
    image_data = None
    image_data_list = []
    if images:
        for img in images:
            content = await img.read()
            encoded = base64.b64encode(content).decode("utf-8")
            image_data_list.append(encoded)
        # Keep first image for backward compatibility (in memory only)
        image_data = image_data_list[0] if image_data_list else None
    
    # Prepare data for storage: save ALL images as JSON list string
    storage_image_data = None
    if image_data_list:
        storage_image_data = json.dumps(image_data_list)

    # Save user message
    user_msg = Message(
        conversation_id=session_id,
        role="user",
        content=message,
        image_data=storage_image_data,  # Store ALL images
    )
    db.add(user_msg)
    await db.commit()
    
    # Load conversation history
    result = await db.execute(
        select(Message)
        .where(Message.conversation_id == session_id)
        .order_by(Message.created_at)
    )
    history = result.scalars().all()
    
    # Build messages list
    messages = []
    for msg in history:
        if msg.role == "user":
            messages.append(HumanMessage(content=msg.content))
        else:
            messages.append(AIMessage(content=msg.content))
    
    # Create initial state for new multi-agent system
    import time
    from backend.agent.state import create_initial_state
    
    initial_state = create_initial_state(session_id, image_data, image_data_list)
    initial_state["messages"] = messages


    # Create Assistant Placeholder message (pending)
    assistant_msg = Message(
        conversation_id=session_id,
        role="assistant",
        content="", # Empty content marks it as "generating" or "pending"
    )
    db.add(assistant_msg)
    await db.commit()
    await db.refresh(assistant_msg)
    assistant_msg_id = assistant_msg.id

    import asyncio
    queue = asyncio.Queue()

    async def run_agent_in_background():
        """Background task that drives the agent and pushes to queue/DB."""
        try:
            # 1. Initial status
            await queue.put({"type": "status", "status": "thinking"})
            
            run_config = create_run_config(session_id)
            final_state = None
            
            # Use astream_events to capture intermediate steps
            async for event in agent_graph.astream_events(initial_state, config=run_config, version="v1"):
                kind = event["event"]
                
                # Capture final_state from any node that returns a valid state
                if kind == "on_chain_end":
                    output = event["data"].get("output")
                    if isinstance(output, dict) and "messages" in output:
                        final_state = output
                              
                elif kind == "on_tool_end":
                    pass

            if not final_state:
                final_state = await agent_graph.ainvoke(initial_state, config=run_config)

            # Extract final response
            full_response = final_state.get("final_response", "")
            if not full_response:
                for msg in reversed(final_state.get("messages", [])):
                    if hasattr(msg, 'content') and isinstance(msg, AIMessage):
                        content = str(msg.content)
                        if content.strip().startswith('{') and '"questions"' in content:
                            continue
                        full_response = content
                        break
            
            if not full_response:
                 full_response = "Xin lỗi, tôi không thể xử lý yêu cầu này."

            # 2. Responding status
            await queue.put({"type": "status", "status": "responding"})

            # 3. Stream tokens to queue individually 
            chunk_size = 5
            for i in range(0, len(full_response), chunk_size):
                chunk = full_response[i:i+chunk_size]
                await queue.put({"type": "token", "content": chunk})
            
            # 4. Save FINAL response to database immediately (resilience!)
            async with AsyncSessionLocal() as save_db:
                from sqlalchemy import update
                await save_db.execute(
                    update(Message)
                    .where(Message.id == assistant_msg_id)
                    .values(content=full_response)
                )
                
                # Update conversation title if needed
                if len(history) <= 1:
                    result = await save_db.execute(
                        select(Conversation).where(Conversation.id == session_id)
                    )
                    conv = result.scalar_one_or_none()
                    if conv and (not conv.title or conv.title == "New Conversation"):
                        conv.title = message[:50] if message else "New Conversation"
                
                await save_db.commit()

            # 5. Done status and metadata
            from backend.agent.state import get_total_duration_ms
            tracking_data = {
                'type': 'done',
                'metadata': {
                    'session_id': session_id,
                    'agents_used': final_state.get('agents_used', []),
                    'tools_called': final_state.get('tools_called', []),
                    'model_calls': final_state.get('model_calls', []),
                    'total_tokens': final_state.get('total_tokens', 0),
                    'total_duration_ms': get_total_duration_ms(final_state),
                    'error': final_state.get('error_message'),
                },
                'memory': {
                    'session_token_count': final_state.get('session_token_count', 0),
                    'context_status': final_state.get('context_status', 'ok'),
                    'context_message': final_state.get('context_message'),
                }
            }
            await queue.put(tracking_data)

        except Exception as e:
            error_msg = f"Xin lỗi, đã có lỗi xảy ra: {str(e)}"
            await queue.put({"type": "token", "content": error_msg})
            await queue.put({"type": "done", "error": str(e)})
            
            # Save error as partially result if needed
            async with AsyncSessionLocal() as save_db:
                from sqlalchemy import update
                await save_db.execute(
                    update(Message)
                    .where(Message.id == assistant_msg_id)
                    .values(content=f"Error: {str(e)}")
                )
                await save_db.commit()
        finally:
            # Signal end of stream
            await queue.put(None)

    # Start the agent task in the background (will continue even if client leaves)
    asyncio.create_task(run_agent_in_background())

    async def stream_from_queue():
        """Generator that reads from the queue and yields to StreamingResponse."""
        while True:
            item = await queue.get()
            if item is None:
                break
            yield f"data: {json.dumps(item)}\n\n"

    return StreamingResponse(
        stream_from_queue(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Session-Id": session_id,
        },
    )


@app.get("/api/rate-limit/{session_id}")
async def get_rate_limit_status(session_id: str):
    """Get current rate limit status for a session."""
    tracker = rate_limiter.get_tracker(session_id)
    tracker.reset_if_needed()
    
    return {
        "requests_this_minute": tracker.requests_this_minute,
        "requests_today": tracker.requests_today,
        "tokens_this_minute": tracker.tokens_this_minute,
        "tokens_today": tracker.tokens_today,
        "limits": {
            "rpm": 30,
            "rpd": 1000,
            "tpm": 8000,
            "tpd": 200000,
        }
    }


@app.get("/api/wolfram-status")
async def get_wolfram_status():
    """Get Wolfram Alpha API usage status (2000 req/month limit)."""
    from backend.tools.wolfram import get_wolfram_status
    return get_wolfram_status()


@app.get("/api/tracing-status")
async def tracing_status():
    """Get LangSmith tracing status."""
    return get_tracing_status()


# Serve static files (frontend) in production
if os.path.exists("frontend/dist"):
    app.mount("/", StaticFiles(directory="frontend/dist", html=True), name="static")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)