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 Contact(models.Model):
    """Contact/person records. Canonical Person table — links to User if person is staff."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    # If this Contact represents a staff member, user is set. External contacts leave it null.
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="contact_profile",
    )
    name = models.CharField(max_length=255)
    email = models.EmailField(blank=True)
    phone = models.CharField(max_length=20, blank=True)
    type = models.CharField(max_length=20, choices=[
        ("individual", "Individual"),
        ("organization", "Organization"),
    ], default="individual")
    company = models.ForeignKey("companies.Company", on_delete=models.SET_NULL, null=True, blank=True, related_name="contacts")
    position = models.CharField(max_length=100, blank=True)
    address = models.TextField(blank=True)
    notes = models.TextField(blank=True)
    tags = models.JSONField(default=list)
    avatar = models.ImageField(upload_to="contact_avatars/", null=True, blank=True)
    visibility = models.CharField(
        max_length=10,
        choices=[("public", "Public"), ("private", "Private")],
        default="public",
        help_text="Private contacts only visible to creator.",
    )
    is_favorite = models.BooleanField(default=False)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "contacts"
        ordering = ["name"]

    def __str__(self):
        return self.name


class Reminder(models.Model):
    """Follow-up reminders attached to a contact."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE, related_name="reminders")
    note = models.CharField(max_length=255)
    remind_at = models.DateTimeField()
    status = models.CharField(
        max_length=10,
        choices=[("pending", "Pending"), ("done", "Done"), ("snoozed", "Snoozed")],
        default="pending",
    )
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "contact_reminders"
        ordering = ["remind_at"]

    def __str__(self):
        return f"{self.contact.name} — {self.note}"