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 Activity(models.Model):
    """Activity tracking for contacts and companies."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    title = models.CharField(max_length=255)
    activity_type = models.CharField(max_length=20, choices=[
        ("call", "Call"),
        ("email", "Email"),
        ("meeting", "Meeting"),
        ("note", "Note"),
        ("task", "Task"),
        ("deadline", "Deadline"),
        ("other", "Other"),
    ])
    description = models.TextField(blank=True)
    contact = models.ForeignKey("contacts.Contact", on_delete=models.CASCADE, null=True, blank=True, related_name="activities")
    company = models.ForeignKey("companies.Company", on_delete=models.CASCADE, null=True, blank=True, related_name="activities")
    project = models.ForeignKey("projects.Project", on_delete=models.CASCADE, null=True, blank=True, related_name="activities")
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="activities")
    due_date = models.DateTimeField(null=True, blank=True)
    is_completed = models.BooleanField(default=False)
    completed_at = models.DateTimeField(null=True, blank=True)
    metadata = models.JSONField(default=dict)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "activities"
        ordering = ["-created_at"]
        indexes = [
            models.Index(fields=["activity_type"]),
            models.Index(fields=["is_completed"]),
            models.Index(fields=["due_date"]),
            models.Index(fields=["project", "due_date"]),
        ]