from django.db import models
from django.conf import settings
from django.utils import timezone
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 Task(models.Model):
    """Task management."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    status = models.CharField(max_length=20, choices=[
        ("todo", "To Do"),
        ("in_progress", "In Progress"),
        ("review", "Review"),
        ("done", "Done"),
        ("cancelled", "Cancelled"),
        ("archived", "Archived"),
    ], default="todo")
    priority = models.CharField(max_length=20, choices=[
        ("low", "Low"),
        ("medium", "Medium"),
        ("high", "High"),
        ("urgent", "Urgent"),
    ], default="medium")
    assignee = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True, related_name="assigned_tasks")
    # Assignee-approval starts the 10-day auto-archive clock; archived_at stamped on (auto/manual) archive.
    approved_at = models.DateTimeField(null=True, blank=True)
    archived_at = models.DateTimeField(null=True, blank=True)
    # Origin marker; "helpdesk" tags tasks created via the General Helpdesk intake.
    source = models.CharField(max_length=20, blank=True, default="")
    project = models.ForeignKey("projects.Project", on_delete=models.CASCADE, null=True, blank=True, related_name="tasks")
    event = models.ForeignKey("events.Event", on_delete=models.CASCADE, null=True, blank=True, related_name="tasks")
    due_date = models.DateTimeField(null=True, blank=True)
    tags = models.JSONField(default=list)
    subtasks = models.JSONField(default=list)
    attachments = models.JSONField(default=list)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="created_tasks")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "tasks"
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["status"]),
            models.Index(fields=["priority"]),
            models.Index(fields=["due_date"]),
            models.Index(fields=["project", "status"]),
            models.Index(fields=["assignee", "status"]),
            models.Index(fields=["approved_at"]),
            models.Index(fields=["source"]),
        ]

    def __str__(self):
        return self.title


class Message(models.Model):
    """Messages/comments on tasks and approvals."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="task_messages")
    content = models.TextField()
    attachments = models.JSONField(default=list)
    is_read = models.BooleanField(default=False)
    related_task = models.ForeignKey(Task, on_delete=models.CASCADE, null=True, blank=True, related_name="messages")
    related_approval = models.ForeignKey("Approval", on_delete=models.CASCADE, null=True, blank=True, related_name="messages")
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "messages"
        ordering = ["created_at"]
        indexes = [
            models.Index(fields=["is_read"]),
            models.Index(fields=["related_task", "created_at"]),
            models.Index(fields=["related_approval", "created_at"]),
        ]


class Approval(models.Model):
    """Approval workflow for tasks and requests."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    requester = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="approval_requests")
    approver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="pending_approvals")
    status = models.CharField(max_length=20, choices=[
        ("pending", "Pending"),
        ("approved", "Approved"),
        ("rejected", "Rejected"),
        ("revised", "Revised"),
    ], default="pending")
    data = models.JSONField(default=dict)
    comment = models.TextField(blank=True)
    resolved_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "approvals"
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["status"]),
        ]