from django.db import models
from django.db.models import Q
from django.db.models.signals import post_save
from django.dispatch import receiver
from smoothschedule.identity.core.models import Tenant

class Site(models.Model):
    tenant = models.OneToOneField(Tenant, on_delete=models.CASCADE, related_name="site")
    primary_domain = models.CharField(max_length=255, blank=True, null=True)
    is_enabled = models.BooleanField(default=True)
    template_key = models.CharField(max_length=100, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"Site for {self.tenant.name}"

    def create_default_page(self):
        """Create a default home page for this site if one doesn't exist."""
        if not self.pages.filter(is_home=True).exists():
            default_content = {
                "content": [
                    {
                        "type": "Header",
                        "props": {
                            "id": "Header-default",
                            "brandText": self.tenant.name,
                            "links": [
                                {"label": "Login", "href": "/login"}
                            ],
                            "variant": "light",
                            "showMobileMenu": True,
                            "sticky": False
                        }
                    },
                    {
                        "type": "Hero",
                        "props": {
                            "id": "Hero-default",
                            "headline": f"Welcome to {self.tenant.name}",
                            "subheadline": "Book your appointment online with ease",
                            "primaryCta": {"text": "Book Now", "href": "#booking"},
                            "variant": "centered",
                            "padding": "large",
                            "backgroundVariant": "gradient-primary"
                        }
                    },
                    {
                        "type": "FullBookingFlow",
                        "props": {
                            "id": "Booking-default",
                            "headline": "Schedule Your Appointment",
                            "subheadline": "Choose a service and time that works for you",
                            "showPrices": True,
                            "showDuration": True,
                            "showDeposits": True,
                            "allowGuestCheckout": True,
                            "anchorId": "booking"
                        }
                    }
                ],
                "root": {}
            }

            Page.objects.create(
                site=self,
                slug="home",
                path="/",
                title="Home",
                is_home=True,
                is_published=True,
                order=0,
                puck_data=default_content
            )

class SiteConfig(models.Model):
    """
    Global theme tokens and chrome settings for a site.
    One per Site, not duplicated per page.
    """
    site = models.OneToOneField(Site, on_delete=models.CASCADE, related_name="config")

    # Theme Tokens (colors, typography, buttons, sections)
    theme = models.JSONField(default=dict)

    # Global Chrome (header and footer configuration)
    header = models.JSONField(default=dict)
    footer = models.JSONField(default=dict)

    version = models.PositiveIntegerField(default=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"Config for {self.site}"

    @staticmethod
    def get_default_theme():
        """Return default theme structure."""
        return {
            'colors': {
                'primary': '#3b82f6',
                'secondary': '#64748b',
                'accent': '#f59e0b',
                'background': '#ffffff',
                'surface': '#f8fafc',
                'text': '#1e293b',
                'textMuted': '#64748b'
            },
            'typography': {
                'fontFamily': 'Inter, system-ui, sans-serif',
                'headingFontFamily': None,
                'baseFontSize': '16px',
                'scale': 1.25
            },
            'buttons': {
                'borderRadius': '8px',
                'primaryStyle': 'solid',
                'secondaryStyle': 'outline'
            },
            'sections': {
                'containerMaxWidth': '1280px',
                'defaultPaddingY': '80px'
            }
        }

    def get_default_header(self):
        """Return default header configuration."""
        return {
            'enabled': True,
            'logo': {'src': '', 'alt': '', 'width': 120},
            'navigation': [
                {'label': 'Home', 'href': '/'},
                {'label': 'Book Now', 'href': '/book', 'style': 'button'}
            ],
            'sticky': True,
            'style': 'default'
        }

    def get_default_footer(self):
        """Return default footer configuration."""
        return {
            'enabled': True,
            'columns': [],
            'copyright': '© {year} {business_name}. All rights reserved.',
            'socialLinks': []
        }

    def get_merged_theme(self):
        """Merge custom theme with defaults."""
        defaults = self.get_default_theme()
        custom = self.theme or {}

        def deep_merge(base, override):
            result = base.copy()
            for key, value in override.items():
                if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                    result[key] = deep_merge(result[key], value)
                else:
                    result[key] = value
            return result

        return deep_merge(defaults, custom)


class Page(models.Model):
    site = models.ForeignKey(Site, related_name="pages", on_delete=models.CASCADE)
    slug = models.SlugField(max_length=255)
    path = models.CharField(max_length=255)
    title = models.CharField(max_length=255)
    is_home = models.BooleanField(default=False)
    is_published = models.BooleanField(default=True)
    order = models.PositiveIntegerField(default=0)
    puck_data = models.JSONField(default=dict)
    version = models.PositiveIntegerField(default=1)

    # SEO Fields
    meta_title = models.CharField(max_length=255, blank=True)
    meta_description = models.TextField(blank=True)
    og_image = models.URLField(blank=True)
    canonical_url = models.URLField(blank=True)
    noindex = models.BooleanField(default=False)

    # Navigation and Chrome
    include_in_nav = models.BooleanField(default=True)
    hide_chrome = models.BooleanField(default=False)  # Landing page mode

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

    class Meta:
        unique_together = ("site", "path")

    def __str__(self):
        return f"{self.title} ({self.path})"

    def get_effective_title(self):
        """Return meta_title if set, otherwise title."""
        return self.meta_title if self.meta_title else self.title

    def get_robots_meta(self):
        """Return robots meta content."""
        if self.noindex:
            return 'noindex, nofollow'
        return 'index, follow'

class Domain(models.Model):
    site = models.ForeignKey(Site, related_name="domains", on_delete=models.CASCADE)
    host = models.CharField(max_length=255, unique=True)
    is_primary = models.BooleanField(default=False)
    is_verified = models.BooleanField(default=False)
    verification_token = models.CharField(max_length=64, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["site"],
                condition=Q(is_primary=True),
                name="unique_primary_domain_per_site",
            )
        ]

    def __str__(self):
        return self.host


@receiver(post_save, sender=Site)
def create_default_page_for_site(sender, instance, created, **kwargs):
    """Automatically create a default home page when a new Site is created."""
    if created:
        instance.create_default_page()


@receiver(post_save, sender=Site)
def create_config_for_site(sender, instance, created, **kwargs):
    """Automatically create SiteConfig when Site is created."""
    if created:
        SiteConfig.objects.get_or_create(site=instance)


@receiver(post_save, sender=Tenant)
def create_site_for_tenant(sender, instance, created, **kwargs):
    """Automatically create a Site with default page for new tenants.

    This ensures ALL tenants (including Free tier) get a default booking page.
    The Site post_save signal will then create the default home page.
    """
    if created:
        Site.objects.get_or_create(tenant=instance)
