"""
Shared helpers for uploading / replacing application supporting documents.

Used by three surfaces:
  * the public Application Status page (applicant, pre-approval),
  * the student profile (post-approval, when an admin has unlocked edits),
  * the admin student-detail page (admin, anytime).
"""
import os
from django import forms

from .models import ApplicationDocument

MAX_DOC_SIZE = 5 * 1024 * 1024  # 5 MB
ALLOWED_EXTENSIONS = ['.pdf', '.jpg', '.jpeg', '.png']


def validate_document_file(f):
    """Raise forms.ValidationError if the upload is too big or the wrong type."""
    if f.size > MAX_DOC_SIZE:
        raise forms.ValidationError('File is larger than 5 MB. Please upload a smaller file.')
    ext = os.path.splitext(f.name)[1].lower()
    if ext not in ALLOWED_EXTENSIONS:
        raise forms.ValidationError('Unsupported file type. Use PDF, JPG or PNG.')
    return f


class DocumentUploadForm(forms.Form):
    document_type = forms.ChoiceField(choices=ApplicationDocument.DOCUMENT_TYPE_CHOICES)
    file = forms.FileField(
        widget=forms.FileInput(attrs={'accept': '.pdf,.jpg,.jpeg,.png'}),
    )

    def clean_file(self):
        return validate_document_file(self.cleaned_data['file'])


def save_application_document(application, document_type, file):
    """Create or replace the single document of `document_type` for `application`.

    Replacing a document resets its verified flag so an admin re-checks it.
    """
    obj, created = ApplicationDocument.objects.update_or_create(
        application=application,
        document_type=document_type,
        defaults={'file': file, 'is_verified': False},
    )
    return obj, created


def document_checklist(application):
    """Return [{type, label, doc}] for every document type, doc=None if missing."""
    existing = {d.document_type: d for d in application.documents.all()}
    return [
        {'type': value, 'label': label, 'doc': existing.get(value)}
        for value, label in ApplicationDocument.DOCUMENT_TYPE_CHOICES
    ]
