from django.db import models
from django.conf import settings
import secrets
import time


def uuid7() -> str:
    """Generate a UUID v7 (time-ordered UUID)."""
    nanoseconds = time.time_ns()
    uuid_int = (nanoseconds << 16) | secrets.randbits(48)
    return f"{uuid_int:032x}"


class MeetingRoom(models.Model):
    """Bookable meeting room."""

    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    name = models.CharField(max_length=255)
    location = models.CharField(max_length=255, blank=True)
    capacity = models.IntegerField(null=True, blank=True)
    facilities = models.JSONField(default=list, blank=True)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "meeting_rooms"
        ordering = ["name"]
        verbose_name = "Meeting room"
        verbose_name_plural = "Meeting rooms"

    def __str__(self):
        return self.name


class Meeting(models.Model):
    """A meeting / room booking. May be independent or linked to an event/project."""

    STATUS_CHOICES = [
        ("scheduled", "Scheduled"),
        ("completed", "Completed"),
        ("cancelled", "Cancelled"),
    ]

    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    room = models.ForeignKey(
        MeetingRoom, on_delete=models.PROTECT, related_name="meetings",
        null=True, blank=True,
    )
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="scheduled")

    event = models.ForeignKey(
        "events.Event", on_delete=models.SET_NULL, related_name="meetings",
        null=True, blank=True,
    )
    project = models.ForeignKey(
        "projects.Project", on_delete=models.SET_NULL, related_name="meetings",
        null=True, blank=True,
    )

    organizer = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL,
        related_name="organized_meetings", null=True, blank=True,
    )
    attendees = models.ManyToManyField(
        settings.AUTH_USER_MODEL, related_name="meetings", blank=True,
    )

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

    class Meta:
        db_table = "meetings"
        ordering = ["-start_time"]
        indexes = [
            models.Index(fields=["room", "start_time", "end_time"]),
            models.Index(fields=["project", "start_time"]),
            models.Index(fields=["event", "start_time"]),
        ]

    def __str__(self):
        return self.title

    def conflicts(self):
        """Return overlapping non-cancelled meetings in the same room."""
        if not self.room_id:
            return Meeting.objects.none()
        qs = Meeting.objects.filter(
            room_id=self.room_id,
            start_time__lt=self.end_time,
            end_time__gt=self.start_time,
        ).exclude(status="cancelled")
        if self.pk:
            qs = qs.exclude(pk=self.pk)
        return qs


class MeetingInvitation(models.Model):
    """Email invitation to a meeting with RSVP tracking."""
    STATUS_CHOICES = [
        ("pending", "Pending"),
        ("accepted", "Accepted"),
        ("declined", "Declined"),
        ("tentative", "Tentative"),
    ]

    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE, related_name="invitations")
    # Internal invitee = linked user (employee); external = contact or just email.
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="meeting_invitations",
    )
    contact = models.ForeignKey(
        "contacts.Contact", on_delete=models.SET_NULL, null=True, blank=True,
        related_name="meeting_invitations",
    )
    email = models.EmailField()
    name = models.CharField(max_length=255)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="pending")
    invited_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    sent_at = models.DateTimeField(null=True, blank=True)
    responded_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "meeting_invitations"
        ordering = ["-created_at"]
        unique_together = ["meeting", "email"]

    def __str__(self):
        return f"{self.email} → {self.meeting.title}"


class MeetingMinutes(models.Model):
    """Minutes of meeting: rich-text body + structured action items (one per meeting)."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    meeting = models.OneToOneField(Meeting, on_delete=models.CASCADE, related_name="minutes")
    body = models.TextField(blank=True)
    # discussion_points: [{"speaker": str, "text": str}] — who said what, for quick note-taking
    discussion_points = models.JSONField(default=list, blank=True)
    # action_items: [{"task": str, "owner": str, "due": "YYYY-MM-DD"|"", "done": bool}]
    action_items = models.JSONField(default=list, blank=True)
    recorded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "meeting_minutes"
        verbose_name = "Meeting minutes"
        verbose_name_plural = "Meeting minutes"

    def __str__(self):
        return f"Minutes — {self.meeting.title}"


class MeetingPresentation(models.Model):
    """A presentation file uploaded by/for a meeting participant."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    meeting = models.ForeignKey(Meeting, on_delete=models.CASCADE, related_name="presentations")
    presenter = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="meeting_presentations",
    )
    presenter_name = models.CharField(max_length=255, blank=True)
    title = models.CharField(max_length=255, blank=True)
    file = models.FileField(upload_to="meeting_presentations/")
    uploaded_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True,
        related_name="uploaded_meeting_presentations",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "meeting_presentations"
        ordering = ["-created_at"]

    def __str__(self):
        return self.title or (self.file.name if self.file else "Presentation")
