import subprocess
import json
import tempfile
import os
import logging
from typing import Dict, List, Any, Optional, Union

# -------------------------------------------------------------------
# Logging setup
# -------------------------------------------------------------------
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("response_iq_api")


from fastapi import FastAPI, HTTPException, BackgroundTasks, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field, validator, HttpUrl


# Import the analysis logic
try:
    from response_iq_analysis import analyze_response
except ImportError:
    # Fallback for when the module isn't strictly importable in some dev environments
    # but in this user's workspace it is adjacent.
    import sys
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    from response_iq_analysis import analyze_response

# -------------------------------------------------------------------
# Models
# -------------------------------------------------------------------
class ResponseIQRequest(BaseModel):
    question: str
    predefinedAnswer: str
    userAnswer: str
    userVoice: Optional[str] = None # URL or Base64 format of the user's voice

class ResponseIQResponse(BaseModel):
    matchScore: int
    comparison: str
    behavioralAnalysis: str
    tonalAnalysis: Optional[str] = None
    visuals: List[str]

# -------------------------------------------------------------------
# FastAPI app
# -------------------------------------------------------------------
app = FastAPI(
    title="Response Iq API",
    description="API for response iq + GPU",
    version="1.0.2"
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/response_iq_data", response_model=ResponseIQResponse)
async def response_iq_data_endpoint(payload: ResponseIQRequest):
    """
    Analyzes the user's answer against a predefined answer.
    Performs text analysis using LLM and tonal analysis if audio is provided.
    """
    # Run analysis (this is synchronous because the analysis module uses blocking requests/librosa)
    # For high concurrency, this should be offloaded to a threadpool or celery, 
    # but for this requirement we run it directly.
    
    logger.info(f"Received request for question: {payload.question[:30]}...")
    
    analysis_result = analyze_response(
        question=payload.question,
        predefined_answer=payload.predefinedAnswer,
        user_answer=payload.userAnswer,
        user_voice_url=payload.userVoice
    )
    
    if "error" in analysis_result:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, 
            detail=analysis_result["error"]
        )

    return analysis_result

