# -*- coding: utf-8 -*-
"""
Pages Models Module

This module contains models for user-created pages functionality.
Allows users to create and manage their own content pages.

Author: Focus Development Team
Version: 1.0.0
Created: 2025-01-01
"""

import uuid
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from django.core.validators import MinLengthValidator

from apps.common.models import BaseModel

User = get_user_model()


class PageStatus(models.TextChoices):
    """Status choices for pages."""
    DRAFT = 'draft', _('Draft')
    PUBLISHED = 'published', _('Published')
    ARCHIVED = 'archived', _('Archived')


class PageVisibility(models.TextChoices):
    """Visibility choices for pages."""
    PRIVATE = 'private', _('Private')
    PUBLIC = 'public', _('Public')
    UNLISTED = 'unlisted', _('Unlisted')


class Page(BaseModel):
    """
    User-created page model.
    
    Allows users to create and manage their own content pages
    with rich text content, custom styling, and sharing options.
    
    Attributes:
        title (str): Page title
        slug (str): URL-friendly identifier
        content (str): Rich text content
        excerpt (str): Short description/summary
        status (str): Publication status
        visibility (str): Who can view the page
        author (User): Page creator
        featured_image (str): URL or path to featured image
        meta_description (str): SEO meta description
        meta_keywords (str): SEO keywords
        custom_css (str): Custom CSS styling
        view_count (int): Number of page views
        is_featured (bool): Whether page is featured
        published_at (datetime): Publication timestamp
        tags (str): Comma-separated tags
    """
    
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
        verbose_name=_('Page ID')
    )
    
    title = models.CharField(
        max_length=200,
        validators=[MinLengthValidator(3)],
        verbose_name=_('Title'),
        help_text=_('Page title (3-200 characters)')
    )
    
    slug = models.SlugField(
        max_length=200,
        unique=True,
        verbose_name=_('Slug'),
        help_text=_('URL-friendly identifier (auto-generated from title)')
    )
    
    content = models.TextField(
        verbose_name=_('Content'),
        help_text=_('Rich text content of the page')
    )
    
    excerpt = models.TextField(
        max_length=500,
        blank=True,
        verbose_name=_('Excerpt'),
        help_text=_('Short description or summary (max 500 characters)')
    )
    
    status = models.CharField(
        max_length=20,
        choices=PageStatus.choices,
        default=PageStatus.DRAFT,
        verbose_name=_('Status'),
        help_text=_('Publication status')
    )
    
    visibility = models.CharField(
        max_length=20,
        choices=PageVisibility.choices,
        default=PageVisibility.PRIVATE,
        verbose_name=_('Visibility'),
        help_text=_('Who can view this page')
    )
    
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='pages',
        verbose_name=_('Author'),
        help_text=_('Page creator')
    )
    
    featured_image = models.URLField(
        blank=True,
        verbose_name=_('Featured Image'),
        help_text=_('URL to featured image')
    )
    
    meta_description = models.CharField(
        max_length=160,
        blank=True,
        verbose_name=_('Meta Description'),
        help_text=_('SEO meta description (max 160 characters)')
    )
    
    meta_keywords = models.CharField(
        max_length=255,
        blank=True,
        verbose_name=_('Meta Keywords'),
        help_text=_('SEO keywords (comma-separated)')
    )
    
    custom_css = models.TextField(
        blank=True,
        verbose_name=_('Custom CSS'),
        help_text=_('Custom CSS styling for this page')
    )
    
    view_count = models.PositiveIntegerField(
        default=0,
        verbose_name=_('View Count'),
        help_text=_('Number of times this page has been viewed')
    )
    
    is_featured = models.BooleanField(
        default=False,
        verbose_name=_('Featured'),
        help_text=_('Whether this page is featured')
    )
    
    published_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name=_('Published At'),
        help_text=_('When the page was published')
    )
    
    tags = models.CharField(
        max_length=500,
        blank=True,
        verbose_name=_('Tags'),
        help_text=_('Comma-separated tags for categorization')
    )
    
    class Meta:
        db_table = 'pages_page'
        verbose_name = _('Page')
        verbose_name_plural = _('Pages')
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['author', 'status']),
            models.Index(fields=['status', 'visibility']),
            models.Index(fields=['published_at']),
            models.Index(fields=['is_featured']),
            models.Index(fields=['slug']),
        ]
    
    def __str__(self):
        return self.title
    
    def save(self, *args, **kwargs):
        """Override save to handle publication timestamp."""
        if self.status == PageStatus.PUBLISHED and not self.published_at:
            self.published_at = timezone.now()
        elif self.status != PageStatus.PUBLISHED:
            self.published_at = None
        super().save(*args, **kwargs)
    
    def get_absolute_url(self):
        """Get the absolute URL for this page."""
        return reverse('pages:page_detail', kwargs={'slug': self.slug})
    
    def increment_view_count(self):
        """Increment the view count for this page."""
        self.view_count += 1
        self.save(update_fields=['view_count'])
    
    def get_tags_list(self):
        """Get tags as a list."""
        if self.tags:
            return [tag.strip() for tag in self.tags.split(',') if tag.strip()]
        return []
    
    def is_published(self):
        """Check if the page is published."""
        return self.status == PageStatus.PUBLISHED
    
    def is_visible_to_user(self, user):
        """Check if the page is visible to a specific user."""
        if self.author == user:
            return True
        
        if self.visibility == PageVisibility.PRIVATE:
            return False
        
        if self.status != PageStatus.PUBLISHED:
            return False
        
        return True
    
    @property
    def word_count(self):
        """Get approximate word count of content."""
        import re
        # Remove HTML tags and count words
        text = re.sub(r'<[^>]+>', '', self.content)
        return len(text.split())
    
    @property
    def reading_time(self):
        """Estimate reading time in minutes (assuming 200 words per minute)."""
        return max(1, self.word_count // 200)
