from fastapi import APIRouter, UploadFile, File, HTTPException, Depends, Query
from src.application.ports.llm_service_port import LLMServicePort
from src.application.dtos.LLM import LLMRequestDTO
from src.dependencies import get_llm_service_by_query, get_llm_service
from src.config import settings
from typing import Optional
import logging
import time  # Required for time.time()

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

router = APIRouter(tags=["charts"])

@router.post("/analyze")
async def analyze_general(
    image: UploadFile = File(...),
    question: str = Query(default="", description="Question about the chart"),
    llm_service: LLMServicePort = Depends(get_llm_service_by_query)
):
    """
    Unified endpoint that works with both Ollama and ChartGemma models.
    Users can select the model via the 'model' query parameter.
    """
    try:
        logger.info(f"Starting analysis with question: {question}")
        logger.info(f"Image filename: {image.filename}, content_type: {image.content_type}")
        
        image_bytes = await image.read()
        logger.info(f"Image size: {len(image_bytes)} bytes")
        
        request = LLMRequestDTO(
            image_bytes=image_bytes,
            question=question
        )
        
        logger.info("Calling LLM service...")
        response = await llm_service.analyze(request)
        logger.info(f"LLM service response received: {response.answer[:100]}...")
        
        return {
            "answer": response.answer,
            "model": response.model_used,
            "processing_time": response.processing_time
        }
        
    except Exception as e:
        logger.error(f"Error in analyze_general: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")

@router.post("/ask")
async def analyze_chart_specialized(
    image: UploadFile = File(...),
    question: str = Query(default="", description="Question about the chart"),
    advanced_analysis: bool = Query(default=False, description="Enable advanced analysis with program of thought")
):
    """
    Specialized endpoint for chart analysis with ChartGemma.
    - advanced_analysis: When True, adds specific prompt engineering for charts
    """
    try:
        logger.info(f"Starting analysis - Question: '{question}', Advanced: {advanced_analysis}")
        
        service = get_llm_service("chartgemma")
        image_bytes = await image.read()
        
        # Enhanced prompt handling
        processed_question = question
        if advanced_analysis:
            processed_question = f"ANALYZE IN DETAIL: {question}"
            logger.info("Using advanced analysis mode")
        
        request = LLMRequestDTO(
            image_bytes=image_bytes,
            question=processed_question
        )
        
        logger.debug("Calling ChartGemma service...")
        start_time = time.time()
        response = await service.analyze(request)
        processing_time = time.time() - start_time
        
        logger.info(f"Analysis completed in {processing_time:.2f}s")
        
        return {
            "answer": response.answer,
            "model": "ChartGemma",
            "analysis_type": "advanced" if advanced_analysis else "basic",
            "processing_time": processing_time  # Now we calculate it ourselves
        }
        
    except Exception as e:
        logger.error(f"Analysis failed: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=500,
            detail=f"Chart analysis error: {str(e)}"
        )
@router.get("/test-chartgemma")
async def test_chartgemma_connection():
    """
    Test endpoint to verify ChartGemma service connection and response structure.
    """
    try:
        logger.info("Testing ChartGemma service connection...")
        
        # Create a simple test request without an image
        service = get_llm_service("chartgemma")
        
        # Test the service with a minimal request
        test_request = LLMRequestDTO(
            image_bytes=b"",  # Empty image for testing
            question="Test question"
        )
        
        response = await service.analyze(test_request)
        
        return {
            "status": "success",
            "service": "ChartGemma",
            "response": response.answer,
            "model_used": response.model_used
        }
        
    except Exception as e:
        logger.error(f"Error testing ChartGemma: {str(e)}", exc_info=True)
        return {
            "status": "error",
            "service": "ChartGemma",
            "error": str(e)
        }

@router.get("/models")
async def list_available_models():
    """
    Endpoint to list available LLM services and their configurations.
    """
    return {
        "available_models": ["ollama", "chartgemma"],
        "default_model": settings.DEFAULT_LLM_MODEL,
        "model_configs": {
            "ollama": {
                "host": settings.OLLAMA_HOST,
                "model": settings.OLLAMA_MODEL,
                "description": "Local Ollama LLM service"
            },
            "chartgemma": {
                "gradio_url": settings.CHARTGEMMA_GRADIO_URL,
                "description": "Specialized chart analysis model"
            }
        }
    }