"""
modal_ftp_backup_nov2026.py -- copy the freshly trained combined models from the staging Modal
volume "yolo-weights-combined" to the Namecheap FTP, into a NEW folder:

    /alidot.online/2capBackupNOV2026/<category>/best.onnx
    /alidot.online/2capBackupNOV2026/<category>/best.pt

Safety:
  - never touches /alidot.online/yolo_weights (the production restore source) or yolo_weights_v2
  - creates only the new folder; an existing file with the same name inside it is overwritten
  - after each upload the remote size is compared with the local size

Usage:
    modal run --profile maeclemennts modal_ftp_backup_nov2026.py                      # every category in the volume
    modal run --profile maeclemennts modal_ftp_backup_nov2026.py --categories car,frog
"""

import ftplib
import os
import time

import modal

app = modal.App("ftp-backup-nov2026")
image = modal.Image.debian_slim(python_version="3.11")
weights_vol = modal.Volume.from_name("yolo-weights-combined", create_if_missing=False)
WEIGHTS_MOUNT = "/weights"

BACKUP_DIR = "/alidot.online/2capBackupNOV2026"
assert "yolo_weights" not in BACKUP_DIR, "refusing to write into the production/staging weight folders"
FILES = ["best.onnx", "best.pt"]


def _connect():
    ftp = ftplib.FTP_TLS(os.environ["FTP_HOST"], os.environ["FTP_USER"], os.environ["FTP_PASS"], timeout=120)
    ftp.prot_p()
    return ftp


def _mkdir(ftp, path):
    try:
        ftp.mkd(path)
    except ftplib.error_perm:
        pass  # already exists


@app.function(
    image=image,
    volumes={WEIGHTS_MOUNT: weights_vol},
    secrets=[modal.Secret.from_name("namecheap-ftp")],
    timeout=1800,
    max_containers=4,  # shared hosting has a low concurrent-login cap
)
def backup_category(name: str) -> dict:
    weights_vol.reload()
    wdir = os.path.join(WEIGHTS_MOUNT, name, "weights")
    result = {"name": name, "files": {}, "status": "ok"}
    for fname in FILES:
        local = os.path.join(wdir, fname)
        if not os.path.isfile(local):
            result["files"][fname] = "missing in volume"
            result["status"] = "incomplete"
            continue
        size = os.path.getsize(local)
        last = None
        for attempt in range(4):
            try:
                ftp = _connect()
                _mkdir(ftp, BACKUP_DIR)
                _mkdir(ftp, f"{BACKUP_DIR}/{name}")
                ftp.cwd(f"{BACKUP_DIR}/{name}")
                with open(local, "rb") as f:
                    ftp.storbinary(f"STOR {fname}", f, blocksize=1024 * 256)
                ftp.voidcmd("TYPE I")
                remote_size = ftp.size(fname)
                ftp.quit()
                if remote_size != size:
                    raise IOError(f"size mismatch: local {size} remote {remote_size}")
                result["files"][fname] = f"ok {size/1e6:.1f}MB"
                last = None
                break
            except Exception as e:
                last = e
                time.sleep(5 * (attempt + 1))
        if last is not None:
            result["files"][fname] = f"FAILED: {str(last)[:100]}"
            result["status"] = "failed"
    return result


@app.local_entrypoint()
def main(categories: str = ""):
    if categories:
        queue = [c.strip() for c in categories.split(",") if c.strip()]
    else:
        queue = [e.path.split("/")[-1] for e in weights_vol.listdir("/") if e.path.split("/")[-1].isalpha()]
        queue = sorted(queue)
    print(f"Backing up {len(queue)} categories to {BACKUP_DIR}\n")
    bad = 0
    for name, res in zip(queue, backup_category.map(queue, return_exceptions=True)):
        if isinstance(res, Exception):
            bad += 1
            print(f"{name:13s} ERROR {type(res).__name__}: {str(res)[:120]}")
            continue
        if res["status"] != "ok":
            bad += 1
        print(f"{name:13s} {res['status']:10s} " + "  ".join(f"{k}={v}" for k, v in res["files"].items()))
    print(f"\nDone: {len(queue) - bad}/{len(queue)} categories fully uploaded to {BACKUP_DIR}")
