import uuid
import secrets
import time

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


def uuid7() -> uuid.UUID:
    nanoseconds = time.time_ns()
    uuid_int = (nanoseconds << 16) | secrets.randbits(48)
    return uuid.UUID(int=uuid_int)


class PdfOperation(models.Model):
    OPERATION_CHOICES = [
        ('merge', 'Merge PDF'),
        ('split', 'Split PDF'),
        ('rotate', 'Rotate PDF'),
        ('reorder', 'Reorder Pages'),
        ('page_numbers', 'Add Page Numbers'),
        ('compress', 'Compress PDF'),
        ('repair', 'Repair PDF'),
        ('pdf_to_word', 'PDF to Word'),
        ('pdf_to_powerpoint', 'PDF to PowerPoint'),
        ('pdf_to_excel', 'PDF to Excel'),
        ('pdf_to_images', 'PDF to Images'),
        ('extract_text', 'Extract Text (OCR)'),
        ('word_to_pdf', 'Word to PDF'),
        ('powerpoint_to_pdf', 'PowerPoint to PDF'),
        ('excel_to_pdf', 'Excel to PDF'),
        ('images_to_pdf', 'Images to PDF'),
        ('html_to_pdf', 'HTML to PDF'),
        ('text_to_pdf', 'Text to PDF'),
        ('protect', 'Protect PDF'),
        ('unlock', 'Unlock PDF'),
        ('sign', 'Sign PDF'),
        ('watermark', 'Watermark PDF'),
        ('redact', 'Redact PDF'),
        ('certify', 'Certify PDF'),
        ('compare', 'Compare PDFs'),
        ('annotate', 'Annotate PDF'),
    ]

    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    operation_type = models.CharField(max_length=32, choices=OPERATION_CHOICES)
    original_filename = models.CharField(max_length=255, blank=True)
    result_filename = models.CharField(max_length=255, blank=True)
    original_size = models.PositiveIntegerField(default=0)
    result_size = models.PositiveIntegerField(default=0)
    page_count = models.PositiveIntegerField(default=0)
    options = models.JSONField(default=dict, blank=True)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        related_name='pdf_operations'
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'pdf_tools_operations'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.get_operation_type_display()} - {self.original_filename}"
