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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
"""
Routes FastAPI pour intégration n8n avec MCP
À ajouter dans votre app.py principal
"""
from fastapi import APIRouter, HTTPException, BackgroundTasks, UploadFile, File
from pydantic import BaseModel
from typing import Dict, Any, Optional, List
import logging
from datetime import datetime

logger = logging.getLogger(__name__)

# Router pour n8n
n8n_router = APIRouter(prefix="/n8n", tags=["n8n"])

# ==================== MODELS ====================

class N8NToolRequest(BaseModel):
    """Request model pour appels n8n"""
    tool_name: str
    arguments: Dict[str, Any]
    context: Optional[Dict[str, Any]] = None
    async_callback: Optional[str] = None  # URL pour callback asynchrone
    
    class Config:
        json_schema_extra = {
            "example": {
                "tool_name": "predict_stance",
                "arguments": {
                    "topic": "climate change",
                    "argument": "We need renewable energy"
                },
                "context": {
                    "session_id": "session_123",
                    "user_id": "user_456"
                }
            }
        }

class N8NBatchRequest(BaseModel):
    """Request pour traitement batch"""
    tool_name: str
    items: List[Dict[str, Any]]
    batch_size: int = 10
    parallel: bool = False
    
    class Config:
        json_schema_extra = {
            "example": {
                "tool_name": "predict_stance",
                "items": [
                    {"topic": "AI", "argument": "AI will help humanity"},
                    {"topic": "AI", "argument": "AI is dangerous"}
                ],
                "batch_size": 10
            }
        }

class N8NPipelineRequest(BaseModel):
    """Request pour pipeline complexe"""
    pipeline_name: str
    input_data: Dict[str, Any]
    steps: List[Dict[str, Any]]
    
    class Config:
        json_schema_extra = {
            "example": {
                "pipeline_name": "debate_analysis",
                "input_data": {
                    "topic": "climate change",
                    "text": "We must act now"
                },
                "steps": [
                    {"tool": "predict_stance", "output_key": "stance"},
                    {"tool": "predict_kpa", "use_previous": True}
                ]
            }
        }

class N8NResponse(BaseModel):
    """Response standardisée pour n8n"""
    success: bool
    data: Optional[Dict[str, Any]] = None
    error: Optional[str] = None
    execution_time: float
    timestamp: datetime = datetime.now()

# ==================== ENDPOINTS ====================

@n8n_router.post("/execute", response_model=N8NResponse)
async def execute_tool(request: N8NToolRequest):
    """
    Endpoint principal pour exécuter un outil MCP depuis n8n
    """
    import time
    start_time = time.time()
    
    try:
        from mcp.server import MCPServer
        from mcp import server  # Importer votre instance MCP
        
        # Exécuter l'outil
        result = await server.call_tool(
            tool_name=request.tool_name,
            arguments=request.arguments
        )
        
        # Ajouter le contexte si fourni
        if request.context:
            result["context"] = request.context
        
        execution_time = time.time() - start_time
        
        return N8NResponse(
            success=True,
            data=result,
            execution_time=execution_time
        )
        
    except Exception as e:
        logger.error(f"Tool execution failed: {str(e)}")
        execution_time = time.time() - start_time
        
        return N8NResponse(
            success=False,
            error=str(e),
            execution_time=execution_time
        )

@n8n_router.post("/batch", response_model=N8NResponse)
async def batch_execute(request: N8NBatchRequest):
    """
    Endpoint pour traitement batch depuis n8n
    """
    import time
    import asyncio
    start_time = time.time()
    
    try:
        from mcp import server
        
        results = []
        
        # Traitement séquentiel ou parallèle
        if request.parallel:
            # Traitement parallèle
            tasks = []
            for item in request.items:
                task = server.call_tool(
                    tool_name=request.tool_name,
                    arguments=item
                )
                tasks.append(task)
            
            results = await asyncio.gather(*tasks, return_exceptions=True)
        else:
            # Traitement séquentiel par batch
            for i in range(0, len(request.items), request.batch_size):
                batch = request.items[i:i + request.batch_size]
                
                for item in batch:
                    try:
                        result = await server.call_tool(
                            tool_name=request.tool_name,
                            arguments=item
                        )
                        results.append(result)
                    except Exception as e:
                        results.append({"error": str(e), "item": item})
        
        execution_time = time.time() - start_time
        
        return N8NResponse(
            success=True,
            data={
                "results": results,
                "total": len(results),
                "successful": sum(1 for r in results if not isinstance(r, Exception) and "error" not in r),
                "failed": sum(1 for r in results if isinstance(r, Exception) or "error" in r)
            },
            execution_time=execution_time
        )
        
    except Exception as e:
        logger.error(f"Batch execution failed: {str(e)}")
        execution_time = time.time() - start_time
        
        return N8NResponse(
            success=False,
            error=str(e),
            execution_time=execution_time
        )

@n8n_router.post("/pipeline", response_model=N8NResponse)
async def execute_pipeline(request: N8NPipelineRequest):
    """
    Endpoint pour exécuter un pipeline multi-étapes
    """
    import time
    start_time = time.time()
    
    try:
        from mcp import server
        
        pipeline_context = {"input": request.input_data}
        results = {}
        
        for step in request.steps:
            tool_name = step["tool"]
            output_key = step.get("output_key", tool_name)
            use_previous = step.get("use_previous", False)
            
            # Préparer les arguments
            if use_previous:
                # Utiliser le résultat de l'étape précédente
                arguments = {**request.input_data, **results}
            else:
                arguments = step.get("arguments", request.input_data)
            
            # Exécuter l'étape
            result = await server.call_tool(
                tool_name=tool_name,
                arguments=arguments
            )
            
            results[output_key] = result
            pipeline_context[output_key] = result
        
        execution_time = time.time() - start_time
        
        return N8NResponse(
            success=True,
            data={
                "pipeline": request.pipeline_name,
                "results": results,
                "context": pipeline_context
            },
            execution_time=execution_time
        )
        
    except Exception as e:
        logger.error(f"Pipeline execution failed: {str(e)}")
        execution_time = time.time() - start_time
        
        return N8NResponse(
            success=False,
            error=str(e),
            execution_time=execution_time
        )

@n8n_router.post("/voice-pipeline")
async def voice_debate_pipeline(
    audio: UploadFile = File(...),
    topic: str = None,
    session_id: str = None
):
    """
    Pipeline complet : Audio → STT → Stance → KPA → Argument Generation → TTS
    Optimisé pour n8n
    """
    import time
    import tempfile
    import os
    start_time = time.time()
    
    try:
        from mcp import server
        from services.stt_service import transcribe_audio
        from services.tts_service import text_to_speech
        
        # 1. Sauvegarder l'audio temporairement
        with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp:
            content = await audio.read()
            tmp.write(content)
            tmp_path = tmp.name
        
        try:
            # 2. Speech-to-Text
            transcription = await transcribe_audio(tmp_path)
            user_text = transcription.get("text", "")
            
            # 3. Stance Detection
            stance_result = await server.call_tool(
                "predict_stance",
                {"topic": topic, "argument": user_text}
            )
            
            # 4. KPA Matching (optionnel)
            # kpa_result = await mcp_server.call_tool(...)
            
            # 5. Generate Counter-Argument
            opposite_stance = "CON" if stance_result["predicted_stance"] == "PRO" else "PRO"
            counter_arg_result = await server.call_tool(
                "generate_argument",
                {
                    "prompt": f"Generate a {opposite_stance} argument about {topic}",
                    "context": f"User said: {user_text}",
                    "stance": opposite_stance
                }
            )
            
            # 6. Text-to-Speech du contre-argument
            tts_audio_path = await text_to_speech(
                counter_arg_result["generated_argument"]
            )
            
            execution_time = time.time() - start_time
            
            return N8NResponse(
                success=True,
                data={
                    "transcription": user_text,
                    "stance_analysis": stance_result,
                    "counter_argument": counter_arg_result,
                    "audio_response_path": tts_audio_path,
                    "session_id": session_id
                },
                execution_time=execution_time
            )
            
        finally:
            # Nettoyer le fichier temporaire
            if os.path.exists(tmp_path):
                os.remove(tmp_path)
        
    except Exception as e:
        logger.error(f"Voice pipeline failed: {str(e)}")
        return N8NResponse(
            success=False,
            error=str(e),
            execution_time=time.time() - start_time
        )

@n8n_router.get("/tools")
async def list_tools():
    """
    Liste tous les outils disponibles (format n8n-friendly)
    """
    try:
        from mcp import server
        tools = await server.list_tools()
        
        return {
            "success": True,
            "tools": tools,
            "total": len(tools)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@n8n_router.get("/resources")
async def list_resources():
    """
    Liste toutes les ressources disponibles (format n8n-friendly)
    """
    try:
        from mcp import server
        resources = await server.list_resources()
        
        return {
            "success": True,
            "resources": resources,
            "total": len(resources)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@n8n_router.get("/health")
async def health_check():
    """
    Health check pour n8n monitoring
    """
    from services.stance_model_manager import stance_model_manager
    from services.label_model_manager import kpa_model_manager
    
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
        "models": {
            "stance": stance_model_manager.model_loaded if stance_model_manager else False,
            "kpa": kpa_model_manager.model_loaded if kpa_model_manager else False
        },
        "services": {
            "stt": True,  # Vérifier si GROQ_API_KEY existe
            "tts": True,
            "chat": True
        }
    }

# ==================== WEBHOOKS ====================

@n8n_router.post("/webhook/debate-result")
async def webhook_debate_result(data: Dict[str, Any], background_tasks: BackgroundTasks):
    """
    Webhook pour recevoir les résultats de débat depuis n8n
    Peut être utilisé pour stocker, notifier, etc.
    """
    logger.info(f"Received debate result webhook: {data}")
    
    # Traiter en arrière-plan
    background_tasks.add_task(process_debate_result, data)
    
    return {"status": "received", "message": "Processing in background"}

async def process_debate_result(data: Dict[str, Any]):
    """
    Traiter les résultats de débat en arrière-plan
    """
    # TODO: Implémenter votre logique
    # - Sauvegarder dans DB
    # - Envoyer des notifications
    # - Mettre à jour des métriques
    logger.info(f"Processing debate result: {data}")

# ==================== EXPORT ====================

def register_n8n_routes(app):
    """
    Enregistrer les routes n8n dans l'application FastAPI
    """
    app.include_router(n8n_router)
    logger.info("n8n routes registered successfully")