"""
Business Models

This module contains all business-related models:
1. BusinessProfile - Extended profile for business users
2. BusinessSearch - Search history and matched influencers
3. Campaign - Marketing campaigns (future)
"""

from django.db import models
from django.conf import settings


class BusinessProfile(models.Model):
    """
    Extended profile for business users

    Stores additional information about businesses beyond the base User model.
    """

    # Link to User
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='business_profile',
        help_text="Link to the business user account"
    )

    # Company Information
    company_name = models.CharField(
        max_length=255,
        help_text="Official company/brand name"
    )

    company_website = models.URLField(
        blank=True,
        null=True,
        help_text="Company website URL"
    )

    industry = models.CharField(
        max_length=100,
        blank=True,
        help_text="Industry/sector (e.g., Fashion, Tech, Food)"
    )

    company_description = models.TextField(
        blank=True,
        help_text="Brief description of the company and products/services"
    )

    # Contact Information
    contact_email = models.EmailField(
        blank=True,
        help_text="Business contact email"
    )

    contact_phone = models.CharField(
        max_length=20,
        blank=True,
        help_text="Business contact phone"
    )

    # Location
    country = models.CharField(
        max_length=100,
        blank=True,
        help_text="Country of operation"
    )

    city = models.CharField(
        max_length=100,
        blank=True,
        help_text="City of operation"
    )

    # Budget Information
    typical_budget_min = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        null=True,
        blank=True,
        help_text="Typical minimum budget for influencer collaborations"
    )

    typical_budget_max = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        null=True,
        blank=True,
        help_text="Typical maximum budget for influencer collaborations"
    )

    # ========================================================================
    # AI PREDICTIONS & EXPLAINABILITY
    # ========================================================================

    ai_predicted_niche = models.CharField(
        max_length=100,
        blank=True,
        null=True,
        db_index=True,
        help_text="AI-predicted niche requirement based on business description"
    )

    ai_predicted_popularity = models.CharField(
        max_length=20,
        blank=True,
        null=True,
        db_index=True,
        help_text="AI-predicted influencer tier requirement based on budget"
    )

    niche_probabilities = models.JSONField(
        default=dict,
        blank=True,
        help_text="Probability distribution for niche requirements"
    )

    popularity_probabilities = models.JSONField(
        default=dict,
        blank=True,
        help_text="Probability distribution for popularity tier requirements"
    )

    niche_recommendation_explanation = models.TextField(
        blank=True,
        null=True,
        help_text="AI-generated explanation for niche recommendations"
    )

    tier_recommendation_explanation = models.TextField(
        blank=True,
        null=True,
        help_text="AI-generated explanation for tier recommendations"
    )

    # Metadata
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Business Profile'
        verbose_name_plural = 'Business Profiles'

    def __str__(self):
        return f"{self.company_name} ({self.user.username})"


class BusinessSearch(models.Model):
    """
    Business Search Model - Stores business search queries and matched influencers.

    When a business searches for influencers, we:
    1. Use LLaMA to predict what niche/popularity they need
    2. Calculate similarity with all influencers
    3. Return ranked matches
    4. Store the search for analytics
    """

    # Business User
    business_user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='business_searches',
        help_text="Business user who performed the search"
    )

    # Search Input
    business_description = models.TextField(
        help_text="Free text describing business needs, target audience, campaign goals"
    )

    budget_min = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        help_text="Minimum budget for influencer collaboration"
    )

    budget_max = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        help_text="Maximum budget for influencer collaboration"
    )

    top_k = models.IntegerField(
        default=10,
        help_text="Number of top matches requested"
    )

    # Target audience geography (from Find Creators form; not company HQ)
    audience_countries = models.JSONField(
        default=list,
        blank=True,
        help_text="Countries the business wants the creator's audience to reach (e.g. ['Pakistan'])",
    )
    audience_cities = models.JSONField(
        default=list,
        blank=True,
        help_text="Cities the business wants the creator's audience to reach",
    )

    # ML Predictions (From LLaMA Zero-Shot)
    predicted_niche_probabilities = models.JSONField(
        default=dict,
        help_text="Predicted niche probabilities from business description"
    )

    predicted_popularity_probabilities = models.JSONField(
        default=dict,
        help_text="Predicted popularity tier from budget range"
    )

    # Search Results
    matched_influencers = models.JSONField(
        default=list,
        help_text="List of matched influencer IDs with similarity scores"
        # Format: [{"influencer_id": 1, "score": 0.95, "niche_score": 0.9, "popularity_score": 0.85}, ...]
    )

    # Metadata
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Business Search'
        verbose_name_plural = 'Business Searches'
        ordering = ['-created_at']

    def __str__(self):
        return f"Search by {self.business_user.username} on {self.created_at.strftime('%Y-%m-%d')}"

    @property
    def top_match(self):
        """Get the top matched influencer"""
        if self.matched_influencers:
            return self.matched_influencers[0]
        return None


class CollaborationRequest(models.Model):
    """
    Tracks collaboration requests from businesses to influencers.
    Business sends request → Influencer accepts/rejects.
    """

    class Status(models.TextChoices):
        PENDING = 'PENDING', 'Pending'
        ACCEPTED = 'ACCEPTED', 'Accepted'
        REJECTED = 'REJECTED', 'Rejected'

    business = models.ForeignKey(
        BusinessProfile,
        on_delete=models.CASCADE,
        related_name='collaboration_requests',
        help_text="Business that initiated the collaboration"
    )
    influencer = models.ForeignKey(
        'influencers.InfluencerProfile',
        on_delete=models.CASCADE,
        related_name='collaboration_requests',
        help_text="Influencer receiving the collaboration request"
    )
    status = models.CharField(
        max_length=10,
        choices=Status.choices,
        default=Status.PENDING,
        db_index=True,
    )
    message = models.TextField(
        blank=True,
        help_text="Message from business describing the collaboration opportunity"
    )
    campaign_description = models.TextField(
        blank=True,
        help_text="Description of the campaign or project"
    )
    budget_offer = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        null=True,
        blank=True,
        help_text="Budget offered for this collaboration"
    )
    response_message = models.TextField(
        blank=True,
        help_text="Response message from the influencer"
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'Collaboration Request'
        verbose_name_plural = 'Collaboration Requests'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.business.company_name} → Creator #{self.influencer.id} ({self.status})"
