"""
ML Client Service for communicating with FastAPI ML Service

This service handles all communication with the FastAPI ML inference service.
It provides methods to:
1. Predict influencer niche and popularity
2. Predict business requirements
3. Handle errors gracefully (fallback to keyword-based prediction if ML service is down)

This is a SHARED service used by both influencers and businesses apps.
"""

import requests
import logging
from typing import Dict, Optional
from django.conf import settings

logger = logging.getLogger(__name__)


class MLClient:
    """Client for communicating with FastAPI ML Service"""
    
    def __init__(self):
        self.base_url = settings.ML_SERVICE_URL
        self.timeout = getattr(settings, 'ML_SERVICE_TIMEOUT', 30)
    
    def predict_influencer(
        self,
        biography: str,
        recent_captions: str,
        recent_hashtags: str,
        followers: int,
        following: int,
        posts_count: int,
        verified: bool,
        avg_likes: float,
        avg_comments: float,
        avg_video_views: float,
        engagement_rate: float
    ) -> Optional[Dict]:
        """
        Call FastAPI to predict influencer niche and popularity
        
        Args:
            biography: Influencer biography
            recent_captions: Concatenated recent post captions
            recent_hashtags: Concatenated recent hashtags
            followers: Follower count
            following: Following count
            posts_count: Total posts count
            verified: Verification status
            avg_likes: Average likes per post
            avg_comments: Average comments per post
            avg_video_views: Average video views
            engagement_rate: Engagement rate percentage
            
        Returns:
            {
                "niche_probabilities": {...},
                "popularity_probabilities": {...},
                "processed_data": {...}
            }
            or None if service is unavailable
        """
        try:
            payload = {
                "biography": biography,
                "recent_captions": recent_captions,
                "recent_hashtags": recent_hashtags,
                "followers": followers,
                "following": following,
                "posts_count": posts_count,
                "verified": verified,
                "avg_likes": avg_likes,
                "avg_comments": avg_comments,
                "avg_video_views": avg_video_views,
                "engagement_rate": engagement_rate
            }
            
            response = requests.post(
                f"{self.base_url}/api/v1/predict/influencer",
                json=payload,
                timeout=self.timeout
            )
            response.raise_for_status()

            result = response.json()
            logger.info(f"ML prediction successful for influencer")
            return result

        except requests.exceptions.RequestException as e:
            logger.error(f"ML Service error: {e}")
            return None
    
    def predict_business_requirements(
        self,
        business_description: str,
        budget_min: float,
        budget_max: float
    ) -> Optional[Dict]:
        """
        Call FastAPI to predict business requirements
        
        Args:
            business_description: Free-form text describing business
            budget_min: Minimum budget
            budget_max: Maximum budget
            
        Returns:
            {
                "niche_probabilities": {...},
                "popularity_probabilities": {...},
                "processed_data": {...}
            }
            or None if service is unavailable
        """
        try:
            payload = {
                "business_description": business_description,
                "budget_min": budget_min,
                "budget_max": budget_max
            }
            
            logger.info(f"Calling ML service for business prediction - "
                       f"Description: '{business_description[:100]}...', Budget: ${budget_min}-${budget_max}")
            
            response = requests.post(
                f"{self.base_url}/api/v1/predict/business",
                json=payload,
                timeout=self.timeout
            )
            response.raise_for_status()
            
            result = response.json()
            top_niche = result.get('processed_data', {}).get('top_niche', 'Unknown')
            top_popularity = result.get('processed_data', {}).get('top_popularity', 'Unknown')
            logger.info(f"ML prediction successful for business requirements - "
                       f"Predicted: {top_niche} / {top_popularity}")
            logger.debug(f"Full ML response: {result}")
            return result
            
        except requests.exceptions.RequestException as e:
            logger.error(f"ML Service error: {e}")
            return None
    
    def health_check(self) -> bool:
        """
        Check if ML service is healthy
        
        Returns:
            True if service is healthy, False otherwise
        """
        try:
            response = requests.get(
                f"{self.base_url}/health",
                timeout=5
            )
            response.raise_for_status()
            return response.json().get('status') == 'healthy'
        except requests.exceptions.RequestException:
            return False

