"""
Prediction endpoints for ML service
"""

from fastapi import APIRouter, HTTPException, Depends
import logging

from ..schemas import (
    InfluencerPredictionRequest,
    BusinessPredictionRequest,
    PredictionResponse
)
from ..dependencies import get_predictor
from ..models.predictor import ModelPredictor

logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("/predict/influencer", response_model=PredictionResponse)
async def predict_influencer(
    request: InfluencerPredictionRequest,
    predictor: ModelPredictor = Depends(get_predictor)
):
    """
    Predict influencer niche and popularity tier
    
    This endpoint uses zero-shot classification with LLaMA 3.2-1B to predict:
    - Niche category (Fashion, Fitness, Food, etc.)
    - Popularity tier (Nano, Micro, Mid, Macro, Mega)
    
    Args:
        request: Influencer data including biography, metrics, etc.
        
    Returns:
        Prediction response with niche and popularity probabilities
    """
    try:
        logger.info(f"Received influencer prediction request")
        
        result = predictor.predict_influencer(
            biography=request.biography,
            recent_captions=request.recent_captions,
            recent_hashtags=request.recent_hashtags,
            followers=request.followers,
            following=request.following,
            posts_count=request.posts_count,
            verified=request.verified,
            avg_likes=request.avg_likes,
            avg_comments=request.avg_comments,
            avg_video_views=request.avg_video_views,
            engagement_rate=request.engagement_rate
        )
        
        logger.info(f"Prediction successful: niche={result['processed_data']['top_niche']}, "
                   f"popularity={result['processed_data']['top_popularity']}")
        
        return PredictionResponse(**result)
        
    except Exception as e:
        logger.error(f"Prediction failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")


@router.post("/predict/business", response_model=PredictionResponse)
async def predict_business(
    request: BusinessPredictionRequest,
    predictor: ModelPredictor = Depends(get_predictor)
):
    """
    Predict business requirements (niche and popularity tier)
    
    This endpoint uses zero-shot classification with LLaMA 3.2-1B to predict:
    - Desired influencer niche based on business description
    - Desired influencer popularity tier based on budget
    
    Args:
        request: Business description and budget range
        
    Returns:
        Prediction response with niche and popularity probabilities
    """
    try:
        logger.info(f"Received business prediction request - Description: '{request.business_description[:100]}...', "
                   f"Budget: ${request.budget_min}-${request.budget_max}")
        
        result = predictor.predict_business(
            business_description=request.business_description,
            budget_min=request.budget_min,
            budget_max=request.budget_max
        )
        
        # Log detailed results
        top_niche = result['processed_data']['top_niche']
        top_popularity = result['processed_data']['top_popularity']
        niche_prob = result['niche_probabilities'].get(top_niche, 0)
        pop_prob = result['popularity_probabilities'].get(top_popularity, 0)
        
        logger.info(f"Prediction successful: niche={top_niche} ({niche_prob:.2%}), "
                   f"popularity={top_popularity} ({pop_prob:.2%})")
        logger.debug(f"Full niche probabilities: {result['niche_probabilities']}")
        logger.debug(f"Full popularity probabilities: {result['popularity_probabilities']}")
        
        return PredictionResponse(**result)
        
    except Exception as e:
        logger.error(f"Prediction failed: {e}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")

