"""One-time migration: move existing résumés from the PUBLIC media folder
(frontend/public/media/resume|resumes) into PRIVATE storage and normalize every
Candidate.resume path to 'resumes/<file>'.

Run once, on each environment that already has résumés on disk:
    ./venv/bin/python migrate_resumes_private.py

Idempotent — files already in private storage are left alone. Safe to re-run.
"""
import os
import shutil
import sys

import django

sys.path.append(os.path.dirname(os.path.abspath(__file__)))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.dev")
django.setup()

from django.conf import settings  # noqa: E402
from apps.candidates.models import Candidate  # noqa: E402


def main():
    public_media = settings.MEDIA_ROOT                       # frontend/public/media
    private_root = settings.PRIVATE_MEDIA_ROOT               # backend/private_media
    dest_dir = os.path.join(private_root, "resumes")
    os.makedirs(dest_dir, exist_ok=True)

    moved = normalized = missing = skipped = 0
    for c in Candidate.objects.exclude(resume="").exclude(resume__isnull=True):
        name = c.resume.name                                  # e.g. 'resume/5_x.pdf' or 'resumes/5_x.pdf'
        base = os.path.basename(name)
        new_name = f"resumes/{base}"
        dest = os.path.join(private_root, new_name)

        if os.path.exists(dest):
            # Already private — just normalize the DB path if needed.
            if name != new_name:
                c.resume.name = new_name
                c.save(update_fields=["resume"])
                normalized += 1
            else:
                skipped += 1
            continue

        # Find the source in the public folder (try both spellings).
        src = None
        for candidate_path in (
            os.path.join(public_media, name),
            os.path.join(public_media, "resume", base),
            os.path.join(public_media, "resumes", base),
        ):
            if os.path.exists(candidate_path):
                src = candidate_path
                break

        if not src:
            print(f"  !! source file missing for candidate {c.id}: {name}")
            missing += 1
            continue

        shutil.copy2(src, dest)
        c.resume.name = new_name
        c.save(update_fields=["resume"])
        moved += 1
        print(f"  moved candidate {c.id}: {name} -> {new_name}")

    print("\n----------------------------------------")
    print(f"  moved      : {moved}")
    print(f"  normalized : {normalized} (already private, path fixed)")
    print(f"  skipped    : {skipped} (already correct)")
    print(f"  missing    : {missing} (no source file found)")
    print("----------------------------------------")
    print("Verify résumés load, then you may delete frontend/public/media/resume and /resumes.")


if __name__ == "__main__":
    main()
