"""Keep candidate résumé uploads in sync with the attachment system.

Older upload paths (registration/apply, profile edit, pipeline add-candidate,
bulk CV upload) set Candidate.resume directly. This signal mirrors any such
résumé into a CandidateAttachment row (pointing at the already-stored file, so
no copy is made) and marks it primary — so every résumé shows up in the
Attachments panel regardless of which flow uploaded it.

Idempotent: it only creates a row when the résumé file has no matching
attachment yet, so repeated candidate saves do nothing.
"""
import os

from django.db.models.signals import post_save
from django.dispatch import receiver

from .models import Candidate, CandidateAttachment


@receiver(post_save, sender=Candidate)
def sync_resume_attachment(sender, instance, **kwargs):
    resume = getattr(instance, "resume", None)
    name = getattr(resume, "name", "") if resume else ""
    if not name:
        return
    try:
        # Already recorded as an attachment? nothing to do.
        if CandidateAttachment.objects.filter(candidate=instance, file=name).exists():
            return
        try:
            size = resume.size or 0
        except Exception:  # noqa: BLE001 — file may be missing on disk
            size = 0
        CandidateAttachment.objects.create(
            candidate=instance, file=name,
            original_filename=os.path.basename(name)[:255],
            kind=CandidateAttachment.Kind.RESUME, is_primary=True, size=size,
        )
        # Only the newest résumé stays primary.
        CandidateAttachment.objects.filter(
            candidate=instance, kind=CandidateAttachment.Kind.RESUME,
        ).exclude(file=name).update(is_primary=False)
    except Exception as err:
        import logging
        logger = logging.getLogger(__name__)
        logger.warning("Could not sync resume attachment for candidate %s: %s", getattr(instance, "id", None), err)

