"""
modal_train_combined.py -- retrain categories on ALL their Roboflow sources combined.

Same training recipe as modal_train_roboflow_v3.py (yolo26n from scratch, A100-80GB,
imgsz 960, 100 epochs, patience 15, anti-false-positive augmentation, no hard negatives),
but each category downloads EVERY source listed for it in combined_sources.json
(old + new datasets), merges them into one single-class dataset, then trains.

Safety:
  - writes ONLY to the staging Modal volume "yolo-weights-combined" (never the
    production "yolo-weights" volume) and does NOT upload to any FTP.
  - Roboflow API keys come from the Modal secret "roboflow-keys-combined" (env K1..K15);
    combined_sources.json only holds key ids, never keys.

Merge rules (per category):
  - only boxes whose class name == the category are kept, remapped to class 0
    (a source with extra classes loses those boxes; a source with NO matching class aborts)
  - polygon/mask labels (SAM3 auto-masks) are converted to the old one-box-per-tile style:
    the mask's centre picks the 3x3 tile, the label becomes that tile's standard 31.3% box
    (old hand-drawn boxes are exactly that; tight mask boxes contradict them and score ~0 mAP50
    against old-style models). Several masks in one tile become one box.
  - exact-duplicate images (md5) are dropped; an image that is in a valid/test split can
    never also be in train (no leakage)
  - file names get an s<i>_ prefix so sources never collide

Usage:
    modal run --detach --profile maeclemennts modal_train_combined.py --categories donkey,frog
    modal run --detach --profile maeclemennts modal_train_combined.py              # every category with >1 source
    modal run --detach --profile maeclemennts modal_train_combined.py --include-single true
"""

import hashlib
import json
import os
import shutil
import time

import modal

app = modal.App("yolo-train-combined")

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-combined", create_if_missing=True)
WEIGHTS_MOUNT = "/weights"
SOURCES_FILE = r"D:\modla\combined_sources.json"

MODEL_WEIGHTS = "yolo26n.pt"
IMG_SIZE = 960
EPOCHS = 100
PATIENCE = 15
STANDARD_BOOST = {"mixup": 0.3, "copy_paste": 0.3, "degrees": 15.0, "shear": 5.0, "cls": 1.0}
EXTRA_BOOST = {"mixup": 0.35, "copy_paste": 0.35, "degrees": 20.0, "shear": 8.0, "cls": 1.5, "hsv_v": 0.5}
IMG_EXT = (".jpg", ".jpeg", ".png", ".bmp", ".webp")


def _names_of(data_yaml_path):
    import yaml

    with open(data_yaml_path) as f:
        cfg = yaml.safe_load(f)
    names = cfg.get("names", [])
    if isinstance(names, dict):
        return {int(k): str(v) for k, v in names.items()}
    return {i: str(n) for i, n in enumerate(names)}


GRID = 3          # captcha = 3x3 tiles
TILE_BOX = 0.313  # the old hand-drawn boxes are one box per tile: ~31.3% x 31.3%, centred on the tile (checked: 100% of them)


def _mask_to_tile_box(parts):
    """Polygon label line ('cls x1 y1 x2 y2 ...') -> one standard tile box in the old labelling style.

    The old datasets box the whole tile an object is in; SAM3 masks hug the object (~4% of the image
    instead of ~10%), so their tight boxes never reach IoU 0.5 with the old style and the two styles
    contradict each other. The mask's centre decides the tile; the box is that tile's standard box."""
    xs = [float(v) for v in parts[1::2]]
    ys = [float(v) for v in parts[2::2]]
    cx, cy = (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2
    col = min(GRID - 1, max(0, int(cx * GRID)))
    row = min(GRID - 1, max(0, int(cy * GRID)))
    return f"0 {(col + 0.5) / GRID:.6f} {(row + 0.5) / GRID:.6f} {TILE_BOX} {TILE_BOX}"


def _merge_sources(src_dirs, category, out_dir):
    """src_dirs: list of (label, dir). Returns stats dict; writes out_dir/data.yaml."""
    import yaml

    cat = category.lower()
    stats = {"per_source": {}, "dupes_dropped": 0, "other_class_boxes_dropped": 0, "masks_converted": 0, "counts": {}}
    plan = []
    for label, d in src_dirs:
        names = _names_of(os.path.join(d, "data.yaml"))
        keep = {i for i, n in names.items() if n.strip().lower() == cat}
        if not keep:
            raise ValueError(f"[{category}] source {label}: no class named '{category}' in {names}")
        plan.append((label, d, keep))
        stats["per_source"][label] = {"train": 0, "valid": 0, "test": 0, "classes": list(names.values())}

    seen = {"valid": set(), "test": set(), "train": set()}
    eval_hashes = set()
    out_counts = {"train": 0, "valid": 0, "test": 0}
    for split in ("valid", "test", "train"):  # eval splits first so train duplicates of them are dropped
        img_out = os.path.join(out_dir, split, "images")
        lbl_out = os.path.join(out_dir, split, "labels")
        os.makedirs(img_out, exist_ok=True)
        os.makedirs(lbl_out, exist_ok=True)
        for si, (label, d, keep) in enumerate(plan):
            img_dir = os.path.join(d, split, "images")
            lbl_dir = os.path.join(d, split, "labels")
            if not os.path.isdir(img_dir):
                continue
            for fname in sorted(os.listdir(img_dir)):
                if not fname.lower().endswith(IMG_EXT):
                    continue
                src_img = os.path.join(img_dir, fname)
                with open(src_img, "rb") as f:
                    h = hashlib.md5(f.read()).hexdigest()
                if h in seen[split] or (split != "valid" and h in eval_hashes):
                    stats["dupes_dropped"] += 1
                    continue
                seen[split].add(h)
                if split != "train":
                    eval_hashes.add(h)
                stem, ext = os.path.splitext(fname)
                new_stem = f"s{si}_{stem}"
                lines_out = []
                lbl = os.path.join(lbl_dir, stem + ".txt")
                if os.path.isfile(lbl):
                    with open(lbl) as f:
                        for line in f.read().splitlines():
                            parts = line.split()
                            if len(parts) < 5 or len(parts) == 6:
                                continue
                            if int(float(parts[0])) not in keep:
                                stats["other_class_boxes_dropped"] += 1
                            elif len(parts) == 5:  # normal box: keep as drawn
                                lines_out.append("0 " + " ".join(parts[1:]))
                            else:  # polygon mask (e.g. SAM3) -> the old one-box-per-tile style
                                lines_out.append(_mask_to_tile_box(parts))
                                stats["masks_converted"] += 1
                    lines_out = list(dict.fromkeys(lines_out))  # two masks in one tile -> one box
                shutil.copy2(src_img, os.path.join(img_out, new_stem + ext))
                with open(os.path.join(lbl_out, new_stem + ".txt"), "w") as f:
                    f.write("\n".join(lines_out) + ("\n" if lines_out else ""))
                out_counts[split] += 1
                stats["per_source"][label][split] += 1

    cfg = {
        "path": out_dir,
        "train": "train/images",
        "val": "valid/images" if out_counts["valid"] else "train/images",
        "nc": 1,
        "names": [category],
    }
    if out_counts["test"]:
        cfg["test"] = "test/images"
    with open(os.path.join(out_dir, "data.yaml"), "w") as f:
        yaml.safe_dump(cfg, f)
    stats["counts"] = out_counts
    return stats


@app.function(
    image=image,
    gpu="A100-80GB",
    volumes={WEIGHTS_MOUNT: weights_vol},
    secrets=[modal.Secret.from_name("roboflow-keys-combined")],
    timeout=7200,
    max_containers=10,
)
def train_category(name: str, sources: list) -> dict:
    from roboflow import Roboflow
    from ultralytics import YOLO

    t_dl = time.time()
    src_dirs = []
    for i, s in enumerate(sources):
        key = os.environ[s["key_id"]]
        loc = f"/tmp/{name}_src{i}"
        last = None
        for attempt in range(3):
            try:
                ds = (Roboflow(api_key=key).workspace(s["workspace"]).project(s["project"])
                      .version(s["version"]).download("yolo26", location=loc))
                break
            except Exception as e:  # transient Roboflow/network errors
                last = e
                time.sleep(5 * (attempt + 1))
        else:
            raise RuntimeError(f"[{name}] download failed for {s['project']} v{s['version']}: {last}")
        src_dirs.append((f"{s['project']}_v{s['version']}", ds.location))

    merged = f"/tmp/{name}_merged"
    stats = _merge_sources(src_dirs, name, merged)
    yaml_path = os.path.join(merged, "data.yaml")
    print(f"[{name}] merged: {stats['counts']} dupes_dropped={stats['dupes_dropped']} "
          f"other_class_boxes_dropped={stats['other_class_boxes_dropped']} "
          f"masks_converted_to_tile_boxes={stats['masks_converted']} "
          f"sources={json.dumps(stats['per_source'])}")
    dl_sec = time.time() - t_dl

    train_kwargs = dict(mixup=0.1, copy_paste=0.1, degrees=0.0, shear=0.0)
    train_kwargs.update(EXTRA_BOOST if name == "squirrel" else STANDARD_BOOST)

    model = YOLO(MODEL_WEIGHTS)
    t0 = time.time()
    model.train(
        data=yaml_path, epochs=EPOCHS, imgsz=IMG_SIZE, batch=-1, 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()

    best_pt = os.path.join(WEIGHTS_MOUNT, name, "weights", "best.pt")
    metrics = model.val(data=yaml_path, imgsz=IMG_SIZE, device=0)
    YOLO(best_pt).export(format="onnx", imgsz=IMG_SIZE, simplify=True)
    weights_vol.commit()

    return {
        "name": name, "status": "done", "n_sources": len(sources),
        "train": stats["counts"]["train"], "valid": stats["counts"]["valid"],
        "dupes_dropped": stats["dupes_dropped"], "download_sec": round(dl_sec, 1),
        "train_sec": round(elapsed, 1), "map50": float(metrics.box.map50),
        "map50_95": float(metrics.box.map),
    }


@app.local_entrypoint()
def main(categories: str = "", include_single: bool = False):
    with open(SOURCES_FILE, encoding="utf-8") as f:
        all_sources = json.load(f)
    if categories:
        queue = [c.strip() for c in categories.split(",") if c.strip()]
        unknown = [c for c in queue if c not in all_sources]
        if unknown:
            raise SystemExit(f"unknown categories: {unknown}")
    else:
        queue = [c for c, lst in all_sources.items() if include_single or len(lst) > 1]
    skipped = [c for c in all_sources if c not in queue]
    print(f"Training {len(queue)} categories (combined sources): {queue}")
    if skipped:
        print(f"Not training {len(skipped)} (nothing new to combine / not requested): {skipped}\n")

    jobs = [(c, all_sources[c]) for c in queue]
    total_sec = 0.0
    for (c, _), res in zip(jobs, train_category.starmap(jobs, return_exceptions=True)):
        if isinstance(res, Exception):
            print(f"{c:13s} FAILED ({type(res).__name__}: {str(res)[:300]})")
            continue
        total_sec += res["train_sec"]
        print(f"{c:13s} srcs={res['n_sources']} train={res['train']:4d} valid={res['valid']:3d} "
              f"dupes={res['dupes_dropped']:3d} mAP50={res['map50']:.3f} mAP50-95={res['map50_95']:.3f} "
              f"dl={res['download_sec']:.0f}s train={res['train_sec']:.0f}s")
    print(f"\nTotal training GPU time: {total_sec/60:.1f} min ({total_sec/3600:.2f} GPU-hours)")
