"""
Business Serializers

This module contains all serializers for business-related models and API requests/responses.
"""

from rest_framework import serializers
from .models import BusinessProfile, BusinessSearch, CollaborationRequest
from influencers.serializers import InfluencerProfileListSerializer, InfluencerProfileSerializer


class BusinessProfileSerializer(serializers.ModelSerializer):
    """
    Serializer for BusinessProfile model
    """
    user_name = serializers.SerializerMethodField()
    user_email = serializers.EmailField(source='user.email', read_only=True)
    
    class Meta:
        model = BusinessProfile
        fields = [
            'id',
            'user',
            'user_name',
            'user_email',
            'company_name',
            'company_website',
            'industry',
            'company_description',
            'contact_email',
            'contact_phone',
            'country',
            'city',
            'typical_budget_min',
            'typical_budget_max',
            # AI predictions & explainability (tier/popularity labels removed for user clarity)
            'ai_predicted_niche',
            'niche_probabilities',
            'niche_recommendation_explanation',
            'created_at',
            'updated_at'
        ]
        read_only_fields = [
            'id',
            'user',
            'ai_predicted_niche',
            'niche_probabilities',
            'niche_recommendation_explanation',
            'created_at',
            'updated_at'
        ]
    
    def get_user_name(self, obj):
        """Get user's full name or username"""
        return obj.user.get_full_name() or obj.user.username


class BusinessMatchingRequestSerializer(serializers.Serializer):
    """
    Serializer for business matching request
    """
    business_description = serializers.CharField(
        required=True,
        help_text="Description of the business and campaign goals"
    )
    budget_min = serializers.FloatField(
        required=True,
        min_value=0,
        help_text="Minimum budget for influencer collaboration"
    )
    budget_max = serializers.FloatField(
        required=True,
        min_value=0,
        help_text="Maximum budget for influencer collaboration"
    )
    top_k = serializers.IntegerField(
        required=False,
        default=10,
        min_value=1,
        max_value=50,
        help_text="Number of top matches to return"
    )
    audience_countries = serializers.ListField(
        child=serializers.CharField(max_length=100),
        required=False,
        default=list,
        help_text="Target audience countries to match against influencer audience breakdown",
    )
    audience_cities = serializers.ListField(
        child=serializers.CharField(max_length=100),
        required=False,
        default=list,
        help_text="Target audience cities to match against influencer audience breakdown",
    )

    def validate(self, data):
        """Validate that budget_max >= budget_min"""
        if data['budget_max'] < data['budget_min']:
            raise serializers.ValidationError(
                "budget_max must be greater than or equal to budget_min"
            )
        for key in ('audience_countries', 'audience_cities'):
            raw = data.get(key) or []
            data[key] = [str(v).strip() for v in raw if str(v).strip()]
        return data


class InfluencerMatchSerializer(serializers.Serializer):
    """
    Serializer for individual influencer match result
    """
    profile = InfluencerProfileListSerializer(read_only=True)
    match_score = serializers.FloatField(
        read_only=True,
        help_text="Overall match score between 0 and 1"
    )
    niche_similarity = serializers.FloatField(
        read_only=True,
        help_text="Niche similarity score"
    )
    budget_fit = serializers.FloatField(
        read_only=True,
        help_text="Budget fit score based on price alignment"
    )
    price_info = serializers.DictField(
        read_only=True,
        help_text="Price position and affordability information",
        required=False
    )
    location_match_score = serializers.FloatField(
        read_only=True,
        required=False,
        help_text="How well the influencer's audience geography matches requested locations (0–1)",
    )


class BusinessSearchSerializer(serializers.ModelSerializer):
    """
    Serializer for BusinessSearch model
    """
    business_user_name = serializers.CharField(source='business_user.username', read_only=True)
    top_match_info = serializers.SerializerMethodField()

    class Meta:
        model = BusinessSearch
        fields = [
            'id',
            'business_user',
            'business_user_name',
            'business_description',
            'budget_min',
            'budget_max',
            'top_k',
            'audience_countries',
            'audience_cities',
            'predicted_niche_probabilities',
            # Note: predicted_popularity_probabilities removed from API response for user clarity
            'matched_influencers',
            'top_match_info',
            'created_at'
        ]
        read_only_fields = ['id', 'business_user', 'created_at']

    def get_top_match_info(self, obj):
        """Get information about the top match"""
        if obj.matched_influencers and len(obj.matched_influencers) > 0:
            return obj.matched_influencers[0]
        return None


class BusinessSearchListSerializer(serializers.ModelSerializer):
    """
    Lightweight serializer for listing business searches
    """
    business_user_name = serializers.CharField(source='business_user.username', read_only=True)
    matches_count = serializers.SerializerMethodField()
    
    class Meta:
        model = BusinessSearch
        fields = [
            'id',
            'business_user_name',
            'business_description',
            'budget_min',
            'budget_max',
            'top_k',
            'audience_countries',
            'audience_cities',
            'matches_count',
            'created_at'
        ]
    
    def get_matches_count(self, obj):
        """Get number of matches"""
        return len(obj.matched_influencers) if obj.matched_influencers else 0


class CollaborationRequestSerializer(serializers.ModelSerializer):
    """Serializer for collaboration requests — full detail view."""
    business_name = serializers.CharField(source='business.company_name', read_only=True)
    business_industry = serializers.CharField(source='business.industry', read_only=True)
    influencer_display = serializers.SerializerMethodField()

    class Meta:
        model = CollaborationRequest
        fields = [
            'id',
            'business',
            'business_name',
            'business_industry',
            'influencer',
            'influencer_display',
            'status',
            'message',
            'campaign_description',
            'budget_offer',
            'response_message',
            'created_at',
            'updated_at',
        ]
        read_only_fields = [
            'id', 'business', 'status',
            'response_message', 'created_at', 'updated_at',
        ]

    def get_influencer_display(self, obj):
        """Show full profile only when accepted, anonymous otherwise."""
        if obj.status == CollaborationRequest.Status.ACCEPTED:
            return InfluencerProfileSerializer(obj.influencer).data
        return InfluencerProfileListSerializer(obj.influencer).data


class CollaborationRequestCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = CollaborationRequest
        fields = ['influencer', 'message', 'campaign_description', 'budget_offer']


class CollaborationResponseSerializer(serializers.Serializer):
    status = serializers.ChoiceField(choices=['ACCEPTED', 'REJECTED'])
    response_message = serializers.CharField(required=False, allow_blank=True, default='')

