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

# 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 specialized analysis with question: {question}, advanced: {advanced_analysis}")
        
        # Force ChartGemma for specialized chart analysis
        service = get_llm_service("chartgemma")
        
        # Enhanced prompt for charts if needed
        processed_question = f"PROGRAM OF THOUGHT: {question}" if advanced_analysis else question
        
        image_bytes = await image.read()
        request = LLMRequestDTO(
            image_bytes=image_bytes,
            question=processed_question
        )
        
        logger.info("Calling ChartGemma service...")
        response = await service.analyze(request)
        logger.info(f"ChartGemma service response received: {response.answer[:100]}...")
        
        return {
            "answer": response.answer,
            "model": "ChartGemma",
            "analysis_type": "advanced" if advanced_analysis else "basic",
            "processing_time": response.processing_time
        }
        
    except Exception as e:
        logger.error(f"Error in analyze_chart_specialized: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Internal server 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"
            }
        }
    }