from django.conf import settings
from django.core.validators import FileExtensionValidator
from django.db import models


class Folder(models.Model):
    """A single-level grouping for customs documents. Archiving (soft-delete)
    keeps the folder's documents and their `folder` FK intact so an archived
    document can still show which folder it used to belong to."""
    name = models.CharField(max_length=255)
    is_archived = models.BooleanField(default=False)
    created_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
        related_name='document_folders_created',
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name


class CustomsDocument(models.Model):
    class Status(models.TextChoices):
        VALIDATED = 'validated', 'Validé'
        NOT_VALIDATED = 'not_validated', 'Non validé'
        PENDING_REVIEW = 'pending_review', 'À confirmer'

    file = models.FileField(
        upload_to='customs_docs/%Y/%m/',
        validators=[FileExtensionValidator(['pdf'])],
    )
    original_filename = models.CharField(max_length=255, blank=True)
    folder = models.ForeignKey(
        Folder, null=True, blank=True, on_delete=models.SET_NULL,
        related_name='documents',
    )
    uploaded_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
        related_name='customs_documents_uploaded',
    )
    uploaded_at = models.DateTimeField(auto_now_add=True)
    status = models.CharField(max_length=15, choices=Status.choices, default=Status.NOT_VALIDATED)
    # Name read from the "Customs Officer" field. Set automatically at upload
    # and overwritable by an admin through the review endpoint.
    officer_name = models.CharField(max_length=255, blank=True, null=True)

    class TextSource(models.TextChoices):
        NATIVE = 'native', 'Texte natif du PDF'
        OCR = 'ocr', 'OCR cloud'
        NONE = 'none', 'Extraction impossible'

    text_source = models.CharField(
        max_length=10, choices=TextSource.choices, default=TextSource.NONE,
        verbose_name='Source du texte',
        help_text="Comment le texte a été obtenu : couche texte du PDF ou OCR cloud.",
    )
    # Raw extracted text, kept so an admin reviewing an "À confirmer" document
    # can see what the pipeline actually read without reopening the PDF.
    extracted_text = models.TextField(
        blank=True, default='',
        verbose_name='Texte extrait',
    )
    auto_classified = models.BooleanField(
        default=True,
        verbose_name='Classé automatiquement',
        help_text="Faux dès qu'un administrateur a corrigé le statut à la main.",
    )

    class Meta:
        ordering = ['-uploaded_at']

    def __str__(self):
        return self.original_filename or f'Document {self.pk}'
