"""
migrate_photos_to_s3.py — copia las fotos que ya están en el disco (PHOTOS_DIR) al bucket de MinIO.

Por qué: en 2026-10 las fotos pasaron a MinIO (core/storage.py) porque el servidor de la app se quedaba sin
disco. Las fotos que ya estaban en el disco tienen que subir una vez, con su FECHA DE LLEGADA (la retención RGPD
cuenta desde ahí: una foto de hace 50 días no puede volver a empezar de cero al subirla).

  python scripts/migrate_photos_to_s3.py                    # simulación: cuenta lo que subiría
  python scripts/migrate_photos_to_s3.py --apply            # sube y comprueba cada archivo (se puede repetir)
  python scripts/migrate_photos_to_s3.py --apply --delete-local
                                                            # además borra del disco lo que ya está comprobado

Lee el bucket de las variables S3_* del .env (con STORAGE_BACKEND=local o s3, da igual). Orden recomendado:
  1. parar la app (o al menos el organizer) para que nadie escriba fotos mientras tanto;
  2. `--apply`, y repetirlo hasta que diga "0 por subir";
  3. poner STORAGE_BACKEND=s3 en el .env y arrancar la app; comprobar galerías y descargas;
  4. `--apply --delete-local` para liberar el disco.
No sube los derivados (miniaturas, vistas previas, caras protegidas `.protect/`): se regeneran solos.
Un archivo que ya está en el bucket con el mismo tamaño no se vuelve a subir.
"""
import argparse
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from core import config, storage  # noqa: E402


def _local_files(root: Path):
    for p in sorted(root.rglob("*")):
        if not p.is_file():
            continue
        rel = p.relative_to(root)
        if ".protect" in rel.parts or p.name.endswith(".tmp"):
            continue
        yield p, storage.Key("photos", *rel.parts)


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--apply", action="store_true", help="sube de verdad")
    ap.add_argument("--delete-local", action="store_true", help="borra del disco lo que ya está comprobado en el bucket")
    args = ap.parse_args()
    if args.delete_local and not args.apply:
        ap.error("--delete-local va con --apply")

    root = config.PHOTOS_DIR
    if not root.is_dir():
        print(f"No hay carpeta de fotos en {root}: nada que migrar.")
        return 0
    target = storage.S3Storage()
    target.check()                                   # el bucket responde y existe el índice
    print(f"Origen : {root}\nDestino: {config.S3_ENDPOINT_URL or 'AWS'} / bucket {target.bucket}")

    todo = done = failed = deleted = 0
    todo_bytes = 0
    for path, key in _local_files(root):
        st = path.stat()
        have = target.stat(key)
        if have is not None and have.size == st.st_size:
            done += 1
        else:
            todo += 1
            todo_bytes += st.st_size
            if not args.apply:
                continue
            try:
                target.put_file(path, key, mtime=st.st_mtime)      # verifies the size after the upload
                done += 1
                have = target.stat(key)
            except Exception as exc:
                failed += 1
                print(f"  ERROR {key}: {exc}")
                continue
        if args.delete_local and have is not None and have.size == st.st_size:
            path.unlink()
            deleted += 1

    if args.delete_local:
        storage.LocalStorage().prune_empty(storage.key("photos"))
    verb = "subidos" if args.apply else "por subir"
    print(f"{todo} archivo(s) {verb} ({todo_bytes / 1048576:.1f} MB), {done} ya en el bucket, {failed} error(es)"
          + (f", {deleted} borrado(s) del disco" if args.delete_local else ""))
    if not args.apply and todo:
        print("Simulación: nada cambió. Repetir con --apply.")
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())
