"""
Mentorship add-on for Learning Path enrollments (optional paid — pricing in Part 3).
Direct Certification Path does not use mentorship.
"""
from django.conf import settings
from django.db import models


SESSION_SCHEDULED = 'scheduled'
SESSION_COMPLETED = 'completed'
SESSION_NO_SHOW = 'no_show'
SESSION_CANCELLED = 'cancelled'
MENTOR_SESSION_STATUS_CHOICES = [
    (SESSION_SCHEDULED, 'Scheduled'),
    (SESSION_COMPLETED, 'Completed'),
    (SESSION_NO_SHOW, 'No-show'),
    (SESSION_CANCELLED, 'Cancelled'),
]

ASSIGNMENT_ACTIVE = 'active'
ASSIGNMENT_COMPLETED = 'completed'
ASSIGNMENT_CANCELLED = 'cancelled'
MENTOR_ASSIGNMENT_STATUS_CHOICES = [
    (ASSIGNMENT_ACTIVE, 'Active'),
    (ASSIGNMENT_COMPLETED, 'Completed'),
    (ASSIGNMENT_CANCELLED, 'Cancelled'),
]


class Mentor(models.Model):
    """Verified mentor profile; can cover categories and/or specific courses."""
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='mentor_profile',
    )
    bio = models.TextField(blank=True)
    expertise_tags = models.CharField(
        max_length=400,
        blank=True,
        help_text='Comma-separated tags, e.g. Laravel, SEO, Figma',
    )
    categories = models.ManyToManyField(
        'courses.Category',
        blank=True,
        related_name='mentors',
        help_text='Categories this mentor is vetted for.',
    )
    courses = models.ManyToManyField(
        'courses.Course',
        blank=True,
        related_name='mentors',
        help_text='Specific exam tracks this mentor supports.',
    )
    is_verified = models.BooleanField(default=False)
    max_active_students = models.PositiveIntegerField(
        default=10,
        help_text='Cap on concurrent Learning Path mentees.',
    )
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['user__full_name', 'user__username']

    def __str__(self):
        return f'Mentor: {self.user.get_display_name()}'

    @property
    def expertise_tag_list(self):
        return [t.strip() for t in self.expertise_tags.split(',') if t.strip()]

    def active_assignment_count(self):
        return self.assignments.filter(status=ASSIGNMENT_ACTIVE).count()

    def has_capacity(self):
        return self.active_assignment_count() < self.max_active_students


class MentorAssignment(models.Model):
    """
    Links a Learning Path candidate to a mentor for a course.
    Created when mentorship add-on is purchased (Part 3 wiring).
    """
    mentor = models.ForeignKey(
        Mentor,
        on_delete=models.CASCADE,
        related_name='assignments',
    )
    student = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='mentor_assignments',
    )
    course = models.ForeignKey(
        'courses.Course',
        on_delete=models.CASCADE,
        related_name='mentor_assignments',
    )
    status = models.CharField(
        max_length=20,
        choices=MENTOR_ASSIGNMENT_STATUS_CHOICES,
        default=ASSIGNMENT_ACTIVE,
    )
    weekly_cadence = models.BooleanField(
        default=True,
        help_text='Default: weekly mentoring sessions.',
    )
    notes = models.TextField(blank=True)
    assigned_at = models.DateTimeField(auto_now_add=True)
    ended_at = models.DateTimeField(null=True, blank=True)

    class Meta:
        ordering = ['-assigned_at']
        constraints = [
            models.UniqueConstraint(
                fields=['student', 'course'],
                condition=models.Q(status='active'),
                name='uniq_active_mentor_assignment_per_course',
            ),
        ]

    def __str__(self):
        return f'{self.student} ↔ {self.mentor} ({self.course})'


class MentorSession(models.Model):
    """Scheduled 1:1 session (Zoom/Meet); mentor or student can reschedule."""
    assignment = models.ForeignKey(
        MentorAssignment,
        on_delete=models.CASCADE,
        related_name='sessions',
    )
    scheduled_at = models.DateTimeField()
    duration_minutes = models.PositiveIntegerField(default=45)
    meeting_link = models.URLField(
        blank=True,
        help_text='Zoom or Google Meet link.',
    )
    status = models.CharField(
        max_length=20,
        choices=MENTOR_SESSION_STATUS_CHOICES,
        default=SESSION_SCHEDULED,
    )
    notes = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['scheduled_at']

    def __str__(self):
        return f'Session {self.scheduled_at:%Y-%m-%d %H:%M} — {self.assignment}'
