from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from django.utils import timezone

class Topic(models.Model):
    name = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.name

class Package(models.Model):
    name = models.CharField(max_length=100)
    is_unlimited = models.BooleanField(default=False, help_text="Unlimited message subscription")
    message_limit = models.IntegerField(default=0, help_text="Message limit (used if not unlimited)")
    days_valid = models.IntegerField(default=30, help_text="Validity duration in days")
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0.0, help_text="Price of package")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name} ({'Unlimited' if self.is_unlimited else self.message_limit} msgs, {self.days_valid} days)"

class Company(models.Model):
    name = models.CharField(max_length=255)
    chatbot_name = models.CharField(max_length=255, default="Assistant")
    welcome_message = models.TextField(default="Hi! Welcome to our site. I am your virtual assistant. Feel free to ask me anything!", help_text="Welcome message shown when visitor opens the chat")
    AI_PROVIDER_CHOICES = [
        ('gemini', 'Google Gemini'),
        ('openai', 'OpenAI'),
    ]
    GEMINI_MODEL_CHOICES = [
        ('gemini-3.5-flash', 'Gemini 3.5 Flash'),
        ('gemini-3.1-flash-lite', 'Gemini 3.1 Flash Lite'),
        ('gemini-3.1-flash', 'Gemini 3.1 Flash'),
        ('gemini-3.1-pro', 'Gemini 3.1 Pro'),
        ('gemini-1.5-flash', 'Gemini 1.5 Flash'),
        ('gemini-1.5-pro', 'Gemini 1.5 Pro'),
    ]
    OPENAI_MODEL_CHOICES = [
        ('gpt-4o', 'GPT-4o'),
        ('gpt-4-turbo', 'GPT-4 Turbo'),
        ('gpt-3.5-turbo', 'GPT-3.5 Turbo'),
    ]
    ai_provider = models.CharField(max_length=20, choices=AI_PROVIDER_CHOICES, default='gemini')
    api_key = models.CharField(max_length=255, blank=True, null=True)
    system_prompt = models.TextField(blank=True, null=True)
    google_sheet_url = models.URLField(max_length=1000, blank=True, null=True, help_text="Public Google Sheet URL (View Only) for live knowledge (Items, Pricing, Stock)")
    model_name = models.CharField(max_length=100, default='gemini-3.5-flash')
    ai_model = models.ForeignKey('AIModel', on_delete=models.SET_NULL, null=True, blank=True, help_text='Select a predefined AI model')
    topics = models.ManyToManyField(Topic, blank=True, related_name='companies')
    allowed_domain = models.CharField(max_length=255, blank=True, null=True, help_text="Authorized domain for widget embedding, e.g. example.com (without https://)")
    icon = models.ImageField(upload_to='chatbot_icons/', blank=True, null=True)
    chatbot_icon = models.ImageField(upload_to='chatbot_button_icons/', blank=True, null=True, help_text="Icon used for the floating chat button")
    WIDGET_POSITION_CHOICES = [
        ('right', 'Bottom Right'),
        ('left', 'Bottom Left'),
    ]
    widget_position = models.CharField(max_length=10, choices=WIDGET_POSITION_CHOICES, default='right')
    widget_bottom_offset = models.PositiveIntegerField(default=24, help_text="Pixels from bottom edge")
    widget_side_offset = models.PositiveIntegerField(default=24, help_text="Pixels from left/right edge")
    widget_button_size = models.PositiveIntegerField(default=60, help_text="Floating button size in pixels")
    widget_panel_width = models.PositiveIntegerField(default=360, help_text="Chat panel width in pixels")
    widget_panel_height = models.PositiveIntegerField(default=480, help_text="Chat panel height in pixels")
    widget_sound_enabled = models.BooleanField(default=True, help_text="Play notification sound on new messages")
    # Comma-separated list of enabled widget positions. Possible values:
    # bottom-right, bottom-left, left-center, right-center
    widget_positions = models.CharField(max_length=255, blank=True, null=True, help_text="Comma-separated enabled positions for the widget (e.g. 'bottom-right,left-center')")
    auto_escalate_via_sms = models.BooleanField(default=False, help_text="When enabled, new escalations will trigger SMS notifications to agents")
    auto_escalate_every_message = models.BooleanField(default=False, help_text="When enabled, every incoming visitor message will create an escalation for agents to pick up")
    show_watermark = models.BooleanField(default=True, help_text="Show 'Powered by ChatLab' watermark footer in chat widget")
    image_limit = models.IntegerField(default=50, help_text="Maximum total media images the company can upload (0 for unlimited)")
    
    # Facebook & WhatsApp Integrations
    fb_messenger_enabled = models.BooleanField(default=False, help_text="Enable Facebook Messenger integration")
    fb_verify_token = models.CharField(max_length=255, blank=True, null=True, help_text="Facebook Webhook Verification Token")
    fb_page_id = models.CharField(max_length=255, blank=True, null=True, help_text="Facebook Page ID")
    fb_page_access_token = models.TextField(blank=True, null=True, help_text="Facebook Page Access Token")
    fb_typing_indicator_enabled = models.BooleanField(default=True, help_text="Show typing '...' animation before bot reply in Messenger")
    fb_mark_seen_enabled = models.BooleanField(default=True, help_text="Send 'Seen' checkmark when message is received in Messenger")
    fb_comment_ai_reply = models.BooleanField(default=True, help_text="Automatically reply to Facebook page comments using AI")
    agent_fb_comments_access = models.BooleanField(default=True, help_text="Show Facebook Comments menu to agents")
    
    whatsapp_enabled = models.BooleanField(default=False, help_text="Enable WhatsApp integration")
    wa_phone_number_id = models.CharField(max_length=255, blank=True, null=True, help_text="WhatsApp Phone Number ID")
    wa_business_account_id = models.CharField(max_length=255, blank=True, null=True, help_text="WhatsApp Business Account ID")
    wa_access_token = models.TextField(blank=True, null=True, help_text="WhatsApp Permanent Access Token")
    
    sitemap_url = models.URLField(max_length=1000, blank=True, null=True, help_text="Sitemap XML link for product scraping")
    ecom_api_url = models.URLField(max_length=1000, blank=True, null=True, help_text="Base URL for E-commerce API")
    ecom_api_key = models.CharField(max_length=255, blank=True, null=True, help_text="Generated API Key for E-commerce")
    subscription_valid_until = models.DateField(blank=True, null=True, help_text="Subscription valid until this date")
    message_limit = models.IntegerField(default=0, help_text="Message limit (0 for unlimited)")
    package = models.ForeignKey('Package', on_delete=models.SET_NULL, null=True, blank=True, related_name='companies')
    message_count = models.IntegerField(default=0, help_text="Total bot messages processed")
    ai_agent_active = models.BooleanField(default=True, help_text="AI agent active for this company")

    @property
    def message_remaining(self):
        if self.message_limit > 0:
            return max(0, self.message_limit - self.message_count)
        return None

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        if not self.fb_verify_token:
            import uuid
            self.fb_verify_token = f"chatlab_{uuid.uuid4().hex[:16]}"
        super().save(*args, **kwargs)

    def __str__(self):
        return self.name

class User(AbstractUser):
    class Role(models.TextChoices):
        SUPERUSER = 'SUPERUSER', 'Superuser'
        ADMIN = 'ADMIN', 'Company Admin'
        AGENT = 'AGENT', 'Agent'

    role = models.CharField(max_length=20, choices=Role.choices, default=Role.AGENT)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True, blank=True, related_name='users')
    agent_name = models.CharField(max_length=255, blank=True, null=True, help_text="Display name for agents - appears in chat header")
    agent_photo = models.ImageField(upload_to='agent_photos/', blank=True, null=True)
    # phone_number removed — SMS delivery is deprecated in this deployment

    def save(self, *args, **kwargs):
        if self.is_superuser:
            self.role = self.Role.SUPERUSER
            self.is_staff = True
        elif self.role == self.Role.SUPERUSER:
            self.is_superuser = True
            self.is_staff = True
        super().save(*args, **kwargs)

class FAQ(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='faqs')
    question = models.CharField(max_length=255)
    answer = models.TextField()

    def __str__(self):
        return f"{self.company.name} FAQ: {self.question}"

class CustomParameter(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='custom_parameters')
    keyword = models.CharField(max_length=255, help_text="The keyword or phrase to match")
    response = models.TextField(help_text="The fixed response to give when keyword matches")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.company.name} Param: {self.keyword}"


class Escalation(models.Model):
    """Represents a visitor request that should be escalated to a human agent."""
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='escalations')
    message = models.TextField()
    visitor_id = models.CharField(max_length=255, blank=True, null=True, help_text='Optional ephemeral visitor identifier')
    is_handled = models.BooleanField(default=False)
    claimed_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='claimed_escalations')
    claimed_at = models.DateTimeField(null=True, blank=True)
    agent_last_typing_at = models.DateTimeField(null=True, blank=True, help_text='Timestamp when agent was last typing (for UI indicator)')
    ai_mode_active = models.BooleanField(default=False, help_text="AI mode active for this claimed conversation")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.company.name} Escalation @ {self.created_at.isoformat()}"


class ChatMessage(models.Model):
    SENDER_CHOICES = [
        ('visitor', 'Visitor'),
        ('bot', 'Bot'),
        ('agent', 'Agent'),
        ('system', 'System'),
    ]
    MESSAGE_TYPE_CHOICES = [
        ('text', 'Text'),
        ('image', 'Image'),
        ('voice', 'Voice'),
        ('file', 'File'),
    ]
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='messages')
    sender = models.CharField(max_length=20, choices=SENDER_CHOICES)
    content = models.TextField(blank=True, null=True)
    visitor_id = models.CharField(max_length=255, blank=True, null=True)
    escalation = models.ForeignKey(Escalation, null=True, blank=True, on_delete=models.SET_NULL, related_name='messages')
    message_type = models.CharField(max_length=20, choices=MESSAGE_TYPE_CHOICES, default='text')
    attachment = models.FileField(upload_to='chat_attachments/%Y/%m/%d/', null=True, blank=True)
    attachment_url = models.URLField(max_length=500, blank=True, null=True)  # For external URLs
    meta_message_id = models.CharField(max_length=255, blank=True, null=True, unique=True, help_text="Unique Meta message ID (mid or wamid) for deduplication")
    created_at = models.DateTimeField(auto_now_add=True)

    DELIVERY_STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('sent', 'Sent'),
        ('failed', 'Failed'),
        ('not_applicable', 'Not Applicable'),
    ]
    delivery_status = models.CharField(max_length=20, choices=DELIVERY_STATUS_CHOICES, default='not_applicable')
    delivery_attempts = models.PositiveIntegerField(default=0)

    def save(self, *args, **kwargs):
        is_new = self.pk is None
        if is_new and self.sender in ['bot', 'agent'] and self.visitor_id:
            if self.visitor_id.startswith('fb_') or self.visitor_id.startswith('wa_'):
                # Mark pending ONLY if not already marked sent or failed by the caller
                if self.delivery_status == 'not_applicable':
                    self.delivery_status = 'pending'
        if is_new and self.sender == 'bot':
            if self.company:
                Company.objects.filter(id=self.company.id).update(message_count=models.F('message_count') + 1)
        super().save(*args, **kwargs)
        if is_new and self.escalation:
            self.escalation.updated_at = timezone.now()
            self.escalation.save(update_fields=['updated_at'])

    def __str__(self):
        return f"{self.company.name} {self.sender} ({self.message_type}) @ {self.created_at.isoformat()}"


class FacebookComment(models.Model):
    """Stores Facebook page feed comments."""
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='facebook_comments')
    comment_id = models.CharField(max_length=255, unique=True)
    post_id = models.CharField(max_length=255)
    sender_id = models.CharField(max_length=255)
    sender_name = models.CharField(max_length=255, blank=True, null=True)
    profile_pic = models.URLField(max_length=1000, blank=True, null=True)
    message = models.TextField()
    is_handled = models.BooleanField(default=False)
    ai_reply = models.TextField(blank=True, null=True, help_text="AI generated reply text")
    replied_at = models.DateTimeField(null=True, blank=True, help_text="Timestamp when reply was sent")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.company.name} - Comment by {self.sender_name}"


class StoreComplaint(models.Model):
    """Stores user complaints that agents/admins can manage."""
    class Status(models.TextChoices):
        OPEN = 'open', 'Open'
        IN_PROGRESS = 'in_progress', 'In Progress'
        RESOLVED = 'resolved', 'Resolved'
        CLOSED = 'closed', 'Closed'

    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='store_complaints')
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    customer_name = models.CharField(max_length=255, blank=True, null=True)
    status = models.CharField(max_length=32, choices=Status.choices, default=Status.OPEN)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='created_complaints')
    updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='updated_complaints')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.company.name} Complaint: {self.title} ({self.status})"


class QuickType(models.Model):
    """Admin-configurable quick type snippets usable in widget and agent chat."""
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='quick_types')
    label = models.CharField(max_length=150, help_text='Short label shown on the button')
    content = models.TextField(help_text='Text to insert/send when the quick type is used')
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-created_at',)

    def __str__(self):
        return f"{self.company.name} QuickType: {self.label}"


class AIModel(models.Model):
    """Superuser-managed AI provider and model configurations."""
    PROVIDER_CHOICES = [
        ('gemini', 'Google Gemini'),
        ('openai', 'OpenAI'),
    ]
    provider = models.CharField(max_length=20, choices=PROVIDER_CHOICES)
    model_name = models.CharField(max_length=150, help_text='Model identifier (e.g., gpt-4o, gemini-2.0-flash)')
    display_name = models.CharField(max_length=150, help_text='Human-readable name for dropdown display')
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        unique_together = ('provider', 'model_name')
        ordering = ('provider', '-created_at')
    
    def __str__(self):
        return f"{self.get_provider_display()} - {self.display_name}"


class Theme(models.Model):
    """Company-specific chat widget theme customization."""
    PRESET_CHOICES = [
        ('dark', 'Dark Theme'),
        ('light', 'Light Theme'),
        ('custom', 'Custom'),
    ]
    company = models.OneToOneField(Company, on_delete=models.CASCADE, related_name='theme')
    preset = models.CharField(max_length=20, choices=PRESET_CHOICES, default='dark')
    
    # Color palette (hex format)
    primary_color = models.CharField(max_length=7, default='#6366f1', help_text='Primary accent color (hex)')
    secondary_color = models.CharField(max_length=7, default='#10b981', help_text='Secondary accent color (hex)')
    background_color = models.CharField(max_length=7, default='#0b0f19', help_text='Main background color (hex)')
    text_primary = models.CharField(max_length=7, default='#f5f5f5', help_text='Primary text color (hex)')
    text_muted = models.CharField(max_length=7, default='#9ca3af', help_text='Muted text color (hex)')
    border_color = models.CharField(max_length=7, default='#374151', help_text='Border color (hex)')
    bot_bubble_bg = models.CharField(max_length=7, default='#1f2937', help_text='Bot message bubble background (hex)')
    user_bubble_bg = models.CharField(max_length=7, default='#6366f1', help_text='User message bubble background (hex)')
    send_button_bg = models.CharField(max_length=7, default='#6366f1', help_text='Send button background color (hex)')
    
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ('-updated_at',)
    
    def __str__(self):
        return f"{self.company.name} - {self.get_preset_display()}"
    
    def get_color_dict(self):
        """Return colors as a dict for easy template rendering."""
        return {
            'primary': self.primary_color,
            'secondary': self.secondary_color,
            'background': self.background_color,
            'text_primary': self.text_primary,
            'text_muted': self.text_muted,
            'border': self.border_color,
            'bot_bubble': self.bot_bubble_bg,
            'user_bubble': self.user_bubble_bg,
            'send_button': self.send_button_bg,
        }


class HeroSlide(models.Model):
    image = models.ImageField(upload_to='hero_slides/', help_text="Image for the hero slider")
    alt_text = models.CharField(max_length=255, blank=True, null=True, help_text="Alt text for the image")
    order = models.IntegerField(default=0, help_text="Order in the slider")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['order', '-created_at']

    def __str__(self):
        return f"Slide {self.order} - {self.alt_text or 'No Alt Text'}"


class SiteSettings(models.Model):
    fb_app_verify_token = models.CharField(max_length=255, blank=True, null=True, help_text="Global Meta Webhook Verification Token")
    privacy_policy = models.TextField(blank=True, null=True, help_text="Global Platform Privacy Policy")
    webhook_logging_enabled = models.BooleanField(default=True, help_text="Enable logging of incoming webhooks to the database (Monitor page)")
    
    # Public Content - Home Page Hero
    hero_badge_text = models.CharField(max_length=255, default="ChatLab AI Sales Agent")
    hero_title = models.TextField(default="Increase Engagement with Your Customers")
    hero_subtitle = models.TextField(default="Help businesses scale their operations and boost sales via intelligent WhatsApp, Messenger, and web chatbots.")
    
    # Public Content - Home Page Features
    home_feature_1_title = models.CharField(max_length=255, default="Omnichannel Integration")
    home_feature_1_desc = models.TextField(default="Seamlessly connect with customers across WhatsApp, Facebook Messenger, and web chatbots from a single platform.")
    home_feature_2_title = models.CharField(max_length=255, default="AI Sales Agent")
    home_feature_2_desc = models.TextField(default="Deploy intelligent AI agents that instantly reply to queries, capture leads, and close sales 24/7 automatically.")
    home_feature_3_title = models.CharField(max_length=255, default="Live Handoff & Monitor")
    home_feature_3_desc = models.TextField(default="Monitor AI conversations in real-time and effortlessly take over control when human intervention is needed.")
    
    # Public Content - Contact Info
    contact_email = models.EmailField(default="info@chat-lab.labxit.com")
    contact_phone = models.CharField(max_length=50, default="+880 1XXX-XXXXXX")
    contact_address = models.TextField(default="123 AI Boulevard, Tech City")
    
    # Public Content - Pricing Plans
    pricing_basic_name = models.CharField(max_length=100, default="Starter")
    pricing_basic_price = models.CharField(max_length=100, default="৳4900/mo")
    pricing_basic_features = models.TextField(default="1 Agent\n1000 Messages/mo\nStandard Support")
    
    pricing_pro_name = models.CharField(max_length=100, default="Professional")
    pricing_pro_price = models.CharField(max_length=100, default="৳9900/mo")
    pricing_pro_features = models.TextField(default="5 Agents\nUnlimited Messages\nPriority Support")
    
    pricing_ent_name = models.CharField(max_length=100, default="Enterprise")
    pricing_ent_price = models.CharField(max_length=100, default="Custom")
    pricing_ent_features = models.TextField(default="Unlimited Agents\nDedicated Account Manager\nCustom Integration")
    logo = models.ImageField(upload_to='site_logos/', blank=True, null=True, help_text="Upload platform logo")
    
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        if not self.fb_app_verify_token:
            import random
            self.fb_app_verify_token = "".join([str(random.randint(0, 9)) for _ in range(12)])
        super().save(*args, **kwargs)

    def __str__(self):
        return "Global Site Settings"


class IntegrationErrorLog(models.Model):
    PLATFORM_CHOICES = [
        ('facebook', 'Facebook Messenger'),
        ('whatsapp', 'WhatsApp Business'),
        ('ai', 'AI Engine (Gemini/OpenAI)'),
    ]
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='error_logs')
    platform = models.CharField(max_length=20, choices=PLATFORM_CHOICES)
    error_type = models.CharField(max_length=100, default='API_ERROR')
    error_message = models.TextField()
    details = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('-created_at',)

    def __str__(self):
        return f"{self.company.name} [{self.get_platform_display()}] @ {self.created_at.isoformat()}"


class WebhookTestLog(models.Model):
    """Tracks test payloads sent from Facebook Developer Portal → Send to Server."""
    SOURCE_CHOICES = [
        ('facebook', 'Facebook'),
        ('whatsapp', 'WhatsApp'),
    ]
    source = models.CharField(max_length=20, choices=SOURCE_CHOICES, default='facebook')
    raw_payload = models.TextField()
    remote_ip = models.GenericIPAddressField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    REPLY_STATUS_CHOICES = [
        ('pending', 'Pending AI Reply'),
        ('replied', 'Replied by AI'),
        ('escalated', 'Escalated to Human'),
        ('failed', 'Failed'),
        ('ignored', 'Ignored/Not Applicable'),
    ]
    reply_status = models.CharField(max_length=20, choices=REPLY_STATUS_CHOICES, default='pending')
    reply_time_seconds = models.FloatField(null=True, blank=True)
    processing_attempts = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ('-created_at',)

    def __str__(self):
        return f"[{self.source.upper()}] Webhook Test @ {self.created_at.isoformat()}"


class Form(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='forms')
    title = models.CharField(max_length=255)
    keyword = models.CharField(max_length=255, help_text="The keyword or phrase that triggers this form in chat")
    is_shared = models.BooleanField(default=False, help_text="Share form submissions with agents")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def save(self, *args, **kwargs):
        if not self.id:
            import random
            while True:
                new_id = random.randint(10000, 99999)
                if not Form.objects.filter(id=new_id).exists():
                    self.id = new_id
                    break
        super().save(*args, **kwargs)

    def __str__(self):
        return f"{self.company.name} - Form: {self.title}"



class FormField(models.Model):
    form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name='fields')
    name = models.CharField(max_length=255, help_text="Label of the field")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.form.title} - Field: {self.name}"


class FormSubmission(models.Model):
    class Status(models.TextChoices):
        PENDING = 'pending', 'Pending'
        IN_PROGRESS = 'in_progress', 'In Progress'
        RESOLVED = 'resolved', 'Resolved'
        CLOSED = 'closed', 'Closed'

    form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name='submissions')
    visitor_id = models.CharField(max_length=255, blank=True, null=True)
    answers = models.JSONField(default=dict)
    status = models.CharField(max_length=32, choices=Status.choices, default=Status.PENDING)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"Submission {self.id} for {self.form.title} ({self.status})"



class FormSession(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    visitor_id = models.CharField(max_length=255)
    form = models.ForeignKey(Form, on_delete=models.CASCADE)
    current_field_index = models.PositiveIntegerField(default=0)
    answers = models.JSONField(default=dict)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"Session for {self.visitor_id} - Form: {self.form.title} (Active: {self.is_active})"

class Product(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='products')
    url = models.URLField(max_length=1000)
    title = models.CharField(max_length=500, blank=True, null=True)
    price = models.CharField(max_length=100, blank=True, null=True)
    brand = models.CharField(max_length=255, blank=True, null=True)
    image_url = models.URLField(max_length=1000, blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('company', 'url')

    def __str__(self):
        return self.title or self.url


def company_media_path(instance, filename):
    company_id = instance.company.id if hasattr(instance, 'company') else instance.company_media.company.id
    return f'company_media/{company_id}/{filename}'

class CompanyMedia(models.Model):
    """Stores images with keywords/taglines for AI retrieval."""
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='media_items')
    image = models.ImageField(upload_to=company_media_path)
    tags = models.TextField(help_text="Comma-separated keywords or taglines (e.g., 'summer menu, drinks')")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.company.name} - Media {self.id}"

class CompanyMediaFile(models.Model):
    """Stores multiple images for a single media keyword group."""
    company_media = models.ForeignKey(CompanyMedia, on_delete=models.CASCADE, related_name='extra_files')
    image = models.ImageField(upload_to=company_media_path)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.company_media.company.name} - Extra Media {self.id}"


class Lead(models.Model):
    name = models.CharField(max_length=255)
    phone = models.CharField(max_length=50)
    page_url = models.URLField(max_length=1000, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.name} - {self.phone}"


class VisitorSessionTopic(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    visitor_id = models.CharField(max_length=255)
    current_topic = models.CharField(max_length=255, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('company', 'visitor_id')

    def __str__(self):
        return f"{self.company.name} - {self.visitor_id} - {self.current_topic}"


class VoiceReply(models.Model):
    """Stores keywords mapped to an audio/voice file for auto-replying."""
    company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='voice_replies')
    keyword = models.CharField(max_length=255, help_text="Keyword or phrase to match (comma-separated keywords supported)")
    audio_file = models.FileField(upload_to='voice_replies/%Y/%m/%d/', help_text="Audio file for the voice reply")
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.company.name} Voice Reply: {self.keyword}"

