from django.db import models
from django.contrib.contenttypes.fields import GenericRelation
from django.utils.text import slugify
from simple_history.models import HistoricalRecords
import pycountry

class Park(models.Model):
    STATUS_CHOICES = [
        ('OPERATING', 'Operating'),
        ('CLOSED_TEMP', 'Temporarily Closed'),
        ('CLOSED_PERM', 'Permanently Closed'),
        ('UNDER_CONSTRUCTION', 'Under Construction'),
        ('DEMOLISHED', 'Demolished'),
        ('RELOCATED', 'Relocated'),  # Added to match Ride model
    ]

    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique=True)
    location = models.CharField(max_length=255)
    country = models.CharField(max_length=2, help_text='Two-letter country code (ISO 3166-1 alpha-2)')
    description = models.TextField(blank=True)
    owner = models.ForeignKey(
        'companies.Company',
        on_delete=models.SET_NULL,
        related_name='parks',
        null=True,
        blank=True
    )
    status = models.CharField(
        max_length=20,
        choices=STATUS_CHOICES,
        default='OPERATING'
    )
    opening_date = models.DateField(null=True, blank=True)
    closing_date = models.DateField(null=True, blank=True)
    operating_season = models.CharField(max_length=255, blank=True)
    size_acres = models.DecimalField(
        max_digits=10,
        decimal_places=2,
        null=True,
        blank=True
    )
    website = models.URLField(blank=True)
    average_rating = models.DecimalField(
        max_digits=3,
        decimal_places=2,
        null=True,
        blank=True
    )
    created_at = models.DateTimeField(auto_now_add=True, null=True)
    updated_at = models.DateTimeField(auto_now=True)
    photos = GenericRelation('media.Photo')
    reviews = GenericRelation('reviews.Review')
    history = HistoricalRecords()

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)

    @classmethod
    def get_by_slug(cls, slug):
        """Get park by current or historical slug"""
        try:
            return cls.objects.get(slug=slug), False
        except cls.DoesNotExist:
            # Check historical slugs
            history = cls.history.filter(slug=slug).order_by('-history_date').first()
            if history:
                return cls.objects.get(id=history.id), True
            raise cls.DoesNotExist("No park found with this slug")

    def get_country_name(self):
        """Get the full country name from the country code"""
        try:
            country = pycountry.countries.get(alpha_2=self.country)
            return country.name if country else self.country
        except:
            return self.country

class ParkArea(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255)
    description = models.TextField(blank=True)
    park = models.ForeignKey(
        Park,
        on_delete=models.CASCADE,
        related_name='areas'
    )
    opening_date = models.DateField(null=True, blank=True)
    closing_date = models.DateField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, null=True)
    updated_at = models.DateTimeField(auto_now=True)
    photos = GenericRelation('media.Photo')
    history = HistoricalRecords()

    class Meta:
        ordering = ['name']
        unique_together = ['park', 'slug']

    def __str__(self):
        return f"{self.park.name} - {self.name}"

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        super().save(*args, **kwargs)

    @classmethod
    def get_by_slug(cls, slug):
        """Get area by current or historical slug"""
        try:
            return cls.objects.get(slug=slug), False
        except cls.DoesNotExist:
            # Check historical slugs
            history = cls.history.filter(slug=slug).order_by('-history_date').first()
            if history:
                return cls.objects.get(id=history.id), True
            raise cls.DoesNotExist("No area found with this slug")
