"""
modal_train_roboflow_v3.py — retrain a subset of categories whose Roboflow project
was updated in place (new images added, new version number). Same exact recipe as
the original modal_train_roboflow.py (100 epochs, patience 15, production
yolo-weights volume, /yolo_weights FTP folder) — just a smaller CATEGORY_MAP with
bumped version numbers for the categories that got new images.

Usage:
    modal run modal_train_roboflow_v3.py --categories parrot --detach --profile maeclemennts   # pilot
    modal run modal_train_roboflow_v3.py --detach --profile maeclemennts                        # all 11
"""

import os
import time
import modal

app = modal.App("yolo-roboflow-training-v3")

image = (
    modal.Image.debian_slim(python_version="3.11")
    .apt_install("libgl1", "libglib2.0-0")
    .pip_install("ultralytics", "roboflow", "pyyaml")
)

weights_vol = modal.Volume.from_name("yolo-weights", create_if_missing=True)
WEIGHTS_MOUNT = "/weights"

hard_neg_vol = modal.Volume.from_name("hard-negatives", create_if_missing=True)
HARD_NEG_MOUNT = "/hard_negatives"

# name -> (key_ref, workspace, project_slug, version) — versions per the latest
# Roboflow export snippets (new images added directly to these existing projects).
CATEGORY_MAP = {
    "chicken":      ("RF_KEY_1", "samm11-airoboticslab-online", "chicken-d9c4u", 3),
    "hippopotamus": ("RF_KEY_1", "samm11-airoboticslab-online", "hippopotamus-ylsnj", 3),
    "airplane":     ("RF_KEY_1", "samm11-airoboticslab-online", "airplane-7by8e", 6),
    "hedgehog":     ("RF_KEY_1", "samm11-airoboticslab-online", "hedgehog-jkpbj", 3),
    "car":          ("RF_KEY_1", "samm11-airoboticslab-online", "car-ntb3z", 5),
    "turkey":       ("RF_KEY_2", "muazajaaza-airoboticslab-online", "turkey-dftno", 5),
    "phone":        ("RF_KEY_2", "muazajaaza-airoboticslab-online", "phone-1sybj", 4),
    "squirrel":     ("RF_KEY_2", "muazajaaza-airoboticslab-online", "squirrel-mjyrc", 3),
    "sheep":        ("RF_KEY_2", "muazajaaza-airoboticslab-online", "sheep-msot6", 4),
    "parrot":       ("RF_KEY_2", "muazajaaza-airoboticslab-online", "parrot-9sylh", 6),
    "kangaroo":     ("RF_KEY_2", "muazajaaza-airoboticslab-online", "kangaroo-mqpos", 4),
}

MODEL_WEIGHTS = "yolo26n.pt"
IMG_SIZE = 960
EPOCHS   = 100
PATIENCE = 15
BATCH    = -1

# Anti-false-positive settings for ALL 11 categories this run: heavier
# geometric/mixing augmentation (forces the model to recognize the object under
# more distortion instead of memorizing exact poses) PLUS a higher classification
# loss weight (cls) so it's pushed harder to get the class right rather than just
# localizing something box-shaped -- the actual lever against false positives,
# not just augmentation. Matches the recipe validated on squirrel/dog previously.
STANDARD_BOOST = {"mixup": 0.3, "copy_paste": 0.3, "degrees": 15.0, "shear": 5.0, "cls": 1.0}
# squirrel was previously flagged as one of the worst false-positive offenders --
# push further than the standard boost.
EXTRA_BOOST    = {"mixup": 0.35, "copy_paste": 0.35, "degrees": 20.0, "shear": 8.0, "cls": 1.5, "hsv_v": 0.5}

AUGMENT_OVERRIDES = {name: STANDARD_BOOST for name in CATEGORY_MAP}
AUGMENT_OVERRIDES["squirrel"] = EXTRA_BOOST


HARD_NEG_REPEAT = 6  # 15x was a net regression vs 6x (see history) -- 6x is
                      # the level that actually helped without over-fitting.


def _add_hard_negatives(dataset_dir: str, neg_dir: str, category_name: str) -> int:
    """Add hard-negative images (real confusers this model false-fired on, e.g. a
    non-parrot bird it mistook for a parrot) into the TRAIN split as background
    images (empty label = 'nothing of this class here'), each repeated
    HARD_NEG_REPEAT times so a small set still meaningfully influences training.
    No-op if this category has no hard-negatives folder yet."""
    import os
    import shutil

    if not os.path.isdir(neg_dir):
        return 0
    out_img = os.path.join(dataset_dir, "train", "images")
    out_lbl = os.path.join(dataset_dir, "train", "labels")
    os.makedirs(out_img, exist_ok=True)
    os.makedirs(out_lbl, exist_ok=True)

    n = 0
    for fname in os.listdir(neg_dir):
        if not fname.lower().endswith((".jpg", ".jpeg", ".png")):
            continue
        src = os.path.join(neg_dir, fname)
        stem_src = os.path.splitext(fname)[0]
        for rep in range(HARD_NEG_REPEAT):
            dst_name = f"hardneg_{stem_src}_r{rep}{os.path.splitext(fname)[1]}"
            shutil.copy2(src, os.path.join(out_img, dst_name))
            dst_stem = os.path.splitext(dst_name)[0]
            open(os.path.join(out_lbl, dst_stem + ".txt"), "w").close()  # empty = background
            n += 1
    print(f"[{category_name}] added {n} hard-negative background images "
          f"({n // HARD_NEG_REPEAT} unique x{HARD_NEG_REPEAT} repeats)")
    return n


@app.function(
    image=image,
    gpu="A100-80GB",
    volumes={WEIGHTS_MOUNT: weights_vol, HARD_NEG_MOUNT: hard_neg_vol},
    secrets=[modal.Secret.from_name("roboflow-keys"), modal.Secret.from_name("namecheap-ftp")],
    timeout=7200,  # generous outer bound (2h) — training should stop itself via `patience` well before this
    max_containers=10,
)
def train_category(name: str) -> dict:
    import yaml
    from roboflow import Roboflow
    from ultralytics import YOLO

    if name not in CATEGORY_MAP:
        return {"name": name, "status": "unknown_category"}

    key_ref, workspace, project_slug, version = CATEGORY_MAP[name]
    api_key = os.environ[key_ref]

    local_dir = f"/tmp/{name}"
    rf = Roboflow(api_key=api_key)
    project = rf.workspace(workspace).project(project_slug)
    dataset = project.version(version).download("yolo26", location=local_dir)

    yaml_path = os.path.join(dataset.location, "data.yaml")
    with open(yaml_path) as f:
        cfg = yaml.safe_load(f)
    cfg["path"] = dataset.location
    with open(yaml_path, "w") as f:
        yaml.safe_dump(cfg, f)

    # Disabled again: tested on parrot v6 (fresh real data) too, still no
    # improvement over the clean run and a small mAP50-95 regression (0.813 vs
    # 0.852). New real data is what actually fixes false positives -- not this.
    USE_HARD_NEGATIVES = False
    if USE_HARD_NEGATIVES:
        neg_dir = os.path.join(HARD_NEG_MOUNT, name)
        _add_hard_negatives(dataset.location, neg_dir, name)

    train_kwargs = dict(
        mixup=0.1,
        copy_paste=0.1,
        degrees=0.0,
        shear=0.0,
    )
    train_kwargs.update(AUGMENT_OVERRIDES.get(name, {}))

    model = YOLO(MODEL_WEIGHTS)
    t0 = time.time()
    model.train(
        data=yaml_path,
        epochs=EPOCHS,
        imgsz=IMG_SIZE,
        batch=BATCH,
        patience=PATIENCE,
        device=0,
        workers=8,
        optimizer="auto",
        cos_lr=True,
        close_mosaic=10,
        cache=True,
        val=True,
        seed=42,
        project=WEIGHTS_MOUNT,
        name=name,
        exist_ok=True,
        verbose=False,
        **train_kwargs,
    )
    elapsed = time.time() - t0
    weights_vol.commit()

    save_dir = os.path.join(WEIGHTS_MOUNT, name)
    best_pt  = os.path.join(save_dir, "weights", "best.pt")
    metrics  = model.val(data=yaml_path, imgsz=IMG_SIZE, device=0)

    best_model = YOLO(best_pt)
    best_model.export(format="onnx", imgsz=IMG_SIZE, simplify=True)
    weights_vol.commit()

    return {
        "name": name,
        "status": "done",
        "elapsed_sec": round(elapsed, 1),
        "map50": float(metrics.box.map50),
        "map50_95": float(metrics.box.map),
        "best_pt": best_pt,
    }


@app.function(
    image=image,
    volumes={WEIGHTS_MOUNT: weights_vol},
    secrets=[modal.Secret.from_name("namecheap-ftp")],
    timeout=600,
    max_containers=5,
)
def backup_to_ftp(name: str) -> dict:
    import ftplib

    weights_dir = os.path.join(WEIGHTS_MOUNT, name, "weights")
    best_pt   = os.path.join(weights_dir, "best.pt")
    best_onnx = os.path.join(weights_dir, "best.onnx")
    if not os.path.isfile(best_pt):
        return {"name": name, "ftp_backup": "skipped: no best.pt found"}

    try:
        host = os.environ["FTP_HOST"]
        user = os.environ["FTP_USER"]
        pw   = os.environ["FTP_PASS"]
        remote_dir = os.environ.get("FTP_REMOTE_DIR", "/yolo_weights")

        ftp = ftplib.FTP_TLS(host, user, pw, timeout=60)
        ftp.prot_p()
        for part in [remote_dir, f"{remote_dir}/{name}"]:
            try:
                ftp.mkd(part)
            except ftplib.error_perm:
                pass
        ftp.cwd(f"{remote_dir}/{name}")
        with open(best_pt, "rb") as f:
            ftp.storbinary("STOR best.pt", f)

        onnx_status = "not found"
        if os.path.isfile(best_onnx):
            with open(best_onnx, "rb") as f:
                ftp.storbinary("STOR best.onnx", f)
            onnx_status = "ok"

        ftp.quit()
        return {"name": name, "ftp_backup": "ok", "onnx_backup": onnx_status}
    except Exception as e:
        return {"name": name, "ftp_backup": f"failed: {e}"}


@app.local_entrypoint()
def main(categories: str = ""):
    queue = [c.strip() for c in categories.split(",") if c.strip()] or list(CATEGORY_MAP.keys())
    print(f"Training {len(queue)} categories: {queue}\n")

    total_sec = 0
    for name, result in zip(queue, train_category.map(queue, return_exceptions=True)):
        if isinstance(result, Exception):
            print(f"{name:15s} TRAINING DID NOT FINISH ({type(result).__name__}: {result})")
            continue
        if result.get("status") != "done":
            print(f"{name:15s} {result.get('status')}")
            continue

        total_sec += result["elapsed_sec"]
        backup = backup_to_ftp.remote(name)
        print(f"{name:15s} mAP50={result['map50']:.3f}  mAP50-95={result['map50_95']:.3f}  "
              f"{result['elapsed_sec']:6.0f}s  ftp={backup.get('ftp_backup')}  "
              f"onnx={backup.get('onnx_backup', '-')}")

    print(f"\nTotal GPU time (completed runs only): {total_sec/60:.1f} min ({total_sec/3600:.2f} GPU-hours)")
