from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form from fastapi.responses import StreamingResponse from typing import Optional, List from pydantic import BaseModel from core.security import get_current_user from api.services.txagent_service import txagent_service import logging logger = logging.getLogger(__name__) router = APIRouter() class ChatRequest(BaseModel): message: str history: Optional[List[dict]] = None patient_id: Optional[str] = None class VoiceOutputRequest(BaseModel): text: str language: str = "en-US" @router.get("/txagent/status") async def get_txagent_status(current_user: dict = Depends(get_current_user)): """Obtient le statut du service TxAgent""" try: status = await txagent_service.get_status() return { "status": "success", "txagent_status": status, "mode": txagent_service.config.get_txagent_mode() } except Exception as e: logger.error(f"Error getting TxAgent status: {e}") raise HTTPException(status_code=500, detail="Failed to get TxAgent status") @router.post("/txagent/chat") async def chat_with_txagent( request: ChatRequest, current_user: dict = Depends(get_current_user) ): """Chat avec TxAgent""" try: # Vérifier que l'utilisateur est médecin ou admin if not any(role in current_user.get('roles', []) for role in ['doctor', 'admin']): raise HTTPException(status_code=403, detail="Only doctors and admins can use TxAgent") response = await txagent_service.chat( message=request.message, history=request.history, patient_id=request.patient_id ) return { "status": "success", "response": response, "mode": txagent_service.config.get_txagent_mode() } except Exception as e: logger.error(f"Error in TxAgent chat: {e}") raise HTTPException(status_code=500, detail="Failed to process chat request") @router.post("/txagent/voice/transcribe") async def transcribe_audio( audio: UploadFile = File(...), current_user: dict = Depends(get_current_user) ): """Transcription vocale avec TxAgent""" try: if not any(role in current_user.get('roles', []) for role in ['doctor', 'admin']): raise HTTPException(status_code=403, detail="Only doctors and admins can use voice features") audio_data = await audio.read() result = await txagent_service.voice_transcribe(audio_data) return { "status": "success", "transcription": result, "mode": txagent_service.config.get_txagent_mode() } except Exception as e: logger.error(f"Error in voice transcription: {e}") raise HTTPException(status_code=500, detail="Failed to transcribe audio") @router.post("/txagent/voice/synthesize") async def synthesize_speech( request: VoiceOutputRequest, current_user: dict = Depends(get_current_user) ): """Synthèse vocale avec TxAgent""" try: if not any(role in current_user.get('roles', []) for role in ['doctor', 'admin']): raise HTTPException(status_code=403, detail="Only doctors and admins can use voice features") audio_data = await txagent_service.voice_synthesize( text=request.text, language=request.language ) return StreamingResponse( iter([audio_data]), media_type="audio/mpeg", headers={ "Content-Disposition": "attachment; filename=synthesized_speech.mp3" } ) except Exception as e: logger.error(f"Error in voice synthesis: {e}") raise HTTPException(status_code=500, detail="Failed to synthesize speech") @router.post("/txagent/patients/analyze") async def analyze_patient_data( patient_data: dict, current_user: dict = Depends(get_current_user) ): """Analyse de données patient avec TxAgent""" try: if not any(role in current_user.get('roles', []) for role in ['doctor', 'admin']): raise HTTPException(status_code=403, detail="Only doctors and admins can use analysis features") analysis = await txagent_service.analyze_patient(patient_data) return { "status": "success", "analysis": analysis, "mode": txagent_service.config.get_txagent_mode() } except Exception as e: logger.error(f"Error in patient analysis: {e}") raise HTTPException(status_code=500, detail="Failed to analyze patient data") @router.get("/txagent/chats") async def get_chats(current_user: dict = Depends(get_current_user)): """Obtient l'historique des chats""" try: if not any(role in current_user.get('roles', []) for role in ['doctor', 'admin']): raise HTTPException(status_code=403, detail="Only doctors and admins can access chats") # Cette fonction devra être implémentée dans le service TxAgent chats = await txagent_service.get_chats() return { "status": "success", "chats": chats, "mode": txagent_service.config.get_txagent_mode() } except Exception as e: logger.error(f"Error getting chats: {e}") raise HTTPException(status_code=500, detail="Failed to get chats") @router.get("/txagent/patients/analysis-results") async def get_analysis_results( risk_filter: Optional[str] = None, current_user: dict = Depends(get_current_user) ): """Obtient les résultats d'analyse des patients""" try: if not any(role in current_user.get('roles', []) for role in ['doctor', 'admin']): raise HTTPException(status_code=403, detail="Only doctors and admins can access analysis results") # Cette fonction devra être implémentée dans le service TxAgent results = await txagent_service.get_analysis_results(risk_filter) return { "status": "success", "results": results, "mode": txagent_service.config.get_txagent_mode() } except Exception as e: logger.error(f"Error getting analysis results: {e}") raise HTTPException(status_code=500, detail="Failed to get analysis results")