from django.db import models
from django.urls import reverse
from django.utils.text import slugify
import re


class Video(models.Model):
    SOURCE_CHOICES = [
        ('youtube', 'YouTube'),
        ('vimeo', 'Vimeo'),
        ('upload', 'Direct Upload'),
    ]

    CATEGORY_CHOICES = [
        ('inspection', 'Inspection Videos'),
        ('property', 'Property Videos'),
        ('educational', 'Educational Videos'),
    ]

    ORIENTATION_CHOICES = [
        ('horizontal', 'Horizontal (16:9) — landscape video'),
        ('vertical', 'Vertical (9:16) — reel/phone video'),
    ]

    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=280, unique=True, blank=True)
    description = models.TextField(blank=True)
    source = models.CharField(max_length=20, choices=SOURCE_CHOICES, default='youtube')
    video_url = models.URLField(blank=True, help_text='YouTube or Vimeo URL')
    video_file = models.FileField(upload_to='videos/', blank=True, null=True,
                                  help_text='Use only for direct uploads')
    thumbnail = models.ImageField(upload_to='videos/thumbnails/', blank=True, null=True)
    duration = models.CharField(max_length=20, blank=True, help_text='e.g. 3:45')
    category = models.CharField(
        max_length=20, choices=CATEGORY_CHOICES, default='property',
        help_text='Categorize this video for filtering on the public site'
    )
    orientation = models.CharField(
        max_length=12, choices=ORIENTATION_CHOICES, default='horizontal',
        help_text='Affects how the video displays on its detail page'
    )

    related_property = models.ForeignKey(
        'properties.Property', on_delete=models.SET_NULL, blank=True, null=True, related_name='videos'
    )
    related_properties = models.ManyToManyField(
        'properties.Property',
        blank=True,
        related_name='featured_in_videos',
        help_text='Properties to feature below this video. Visitors can click directly to inquire.'
    )

    highlights = models.TextField(
        blank=True,
        help_text='Optional. One per line. Format: "icon|label|value" '
                  'e.g. "bi-tag|Starting Price|₦4.5M". Displayed as a highlight strip on the detail page.'
    )

    is_featured = models.BooleanField(default=False)
    is_published = models.BooleanField(default=True)
    views_count = models.PositiveIntegerField(default=0)

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

    class Meta:
        ordering = ['-created_at']

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            base = slugify(self.title)[:240]
            slug = base
            i = 1
            while Video.objects.filter(slug=slug).exclude(pk=self.pk).exists():
                slug = f"{base}-{i}"
                i += 1
            self.slug = slug
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('videos:detail', kwargs={'slug': self.slug})

    @property
    def embed_url(self):
        """Return iframe-ready embed URL for YouTube/Vimeo."""
        if self.source == 'youtube' and self.video_url:
            # Extract YouTube ID
            m = re.search(r'(?:v=|youtu\.be/|embed/)([\w-]{11})', self.video_url)
            if m:
                return f"https://www.youtube.com/embed/{m.group(1)}"
        if self.source == 'vimeo' and self.video_url:
            m = re.search(r'vimeo\.com/(\d+)', self.video_url)
            if m:
                return f"https://player.vimeo.com/video/{m.group(1)}"
        return self.video_url

    def get_highlights_list(self):
        if not self.highlights:
            return []
        items = []
        for line in self.highlights.strip().split('\n'):
            parts = [p.strip() for p in line.split('|')]
            if len(parts) >= 3:
                items.append({'icon': parts[0], 'label': parts[1], 'value': parts[2]})
        return items

    @property
    def is_iframe(self):
        return self.source in ('youtube', 'vimeo')
