"""
modal_train_fp_variants.py -- anti-false-positive experiments for ONE category at a time:
several recipes x seeds on the combined sources PLUS real, hand-verified production grids
(/extra/<cat>; a held-out part of the real grids is never given to training).
Writes to the staging volume only, as <category>__<recipe>_s<seed>.  No FTP, no servers.
(derived from modal_train_combined.py -- the merge code below is identical)

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-fp-variants")

image = (
    modal.Image.debian_slim(python_version="3.11")
    .apt_install("libgl1", "libglib2.0-0")
    .pip_install("ultralytics", "roboflow", "pyyaml")
    .add_local_dir("C:/Users/MK/AppData/Local/Temp/claude/D--ClaudeCode/36cdf82a-7aef-4e24-a790-3bab8d0a1b28/scratchpad/allcats/extra", remote_path="/extra")
)

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



RECIPES = {
    # the ORIGINAL recipe the old frog model was trained with
    "light": dict(mixup=0.1, copy_paste=0.1, degrees=0.0, shear=0.0, cls=0.5),
    # the v3 anti-false-positive boost (what the old hippo and the first new frog used)
    "boost": dict(STANDARD_BOOST),
    # heavy: stronger geometry/colour/erasing, longer training so it gets past the early peak
    "bigaug": dict(mixup=0.2, copy_paste=0.3, degrees=10.0, shear=3.0, scale=0.7, translate=0.2,
                   hsv_h=0.03, hsv_s=0.8, hsv_v=0.5, erasing=0.5, fliplr=0.5, cls=1.0,
                   close_mosaic=15, epochs=150, patience=40),
}
EXTRA_REPEAT = 2  # real in-distribution grids are rare, show each twice per epoch


def _add_extra_real(merged_dir, extra_dir):
    n = 0
    for fname in sorted(os.listdir(os.path.join(extra_dir, "images"))):
        stem, ext = os.path.splitext(fname)
        lbl = os.path.join(extra_dir, "labels", stem + ".txt")
        for rep in range(EXTRA_REPEAT):
            for sub, src in (("images", os.path.join(extra_dir, "images", fname)), ("labels", lbl)):
                dst_dir = os.path.join(merged_dir, "train", sub)
                os.makedirs(dst_dir, exist_ok=True)
                dst = os.path.join(dst_dir, f"{stem}_x{rep}" + (ext if sub == "images" else ".txt"))
                shutil.copy2(src, dst)
            n += 1
    return n


@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_variant(category: str, recipe: str, seed: int, use_extra: bool, sources: list,
                  min_epochs: int = 0) -> dict:
    from roboflow import Roboflow
    from ultralytics import YOLO

    src_dirs = []
    for i, s in enumerate(sources):
        key = os.environ[s["key_id"]]
        loc = f"/tmp/{category}_{recipe}_{seed}_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:
                last = e
                time.sleep(5 * (attempt + 1))
        else:
            raise RuntimeError(f"download failed for {s['project']}: {last}")
        src_dirs.append((f"{s['project']}_v{s['version']}", ds.location))

    merged = f"/tmp/{category}_{recipe}_{seed}_merged"
    stats = _merge_sources(src_dirs, category, merged)
    n_extra = _add_extra_real(merged, f"/extra/{category}") if use_extra else 0
    yaml_path = os.path.join(merged, "data.yaml")
    print(f"[{category}/{recipe}/s{seed}] merged {stats['counts']} + extra_real_train_images={n_extra}")

    kw = dict(RECIPES[recipe])
    epochs = kw.pop("epochs", EPOCHS)
    patience = kw.pop("patience", PATIENCE)
    if min_epochs:  # patience = min_epochs guarantees at least min_epochs+1 epochs before early stop
        patience = max(patience, min_epochs)
        epochs = max(epochs, min_epochs + 30)
    close_mosaic = kw.pop("close_mosaic", 10)
    run_name = f"{category}__{recipe}_s{seed}" + ("" if use_extra else "_noextra") + (f"_min{min_epochs}" if min_epochs else "")

    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=close_mosaic, cache=True,
        val=True, seed=seed, project=WEIGHTS_MOUNT, name=run_name, exist_ok=True, verbose=False, **kw,
    )
    elapsed = time.time() - t0
    weights_vol.commit()
    best_pt = os.path.join(WEIGHTS_MOUNT, run_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 {"run": run_name, "train": stats["counts"]["train"] + n_extra, "train_sec": round(elapsed, 1),
            "map50": float(metrics.box.map50), "map50_95": float(metrics.box.map)}


@app.local_entrypoint()
def main(category: str, recipes: str = "light,boost,bigaug", seeds: str = "1,2", use_extra: bool = True,
         min_epochs: int = 0):
    with open(SOURCES_FILE, encoding="utf-8") as f:
        sources = json.load(f)[category]
    jobs = [(category, r, int(s), use_extra, sources, min_epochs)
            for r in recipes.split(",") for s in seeds.split(",")]
    print(f"{len(jobs)} runs for {category}: {[(j[1], j[2]) for j in jobs]}  use_extra={use_extra} min_epochs={min_epochs}")
    for j, res in zip(jobs, train_variant.starmap(jobs, return_exceptions=True)):
        if isinstance(res, Exception):
            print(f"{j[1]:7s} s{j[2]} FAILED {type(res).__name__}: {str(res)[:300]}")
        else:
            print(f"{res['run']:32s} train_imgs={res['train']:4d} mAP50={res['map50']:.3f} "
                  f"mAP50-95={res['map50_95']:.3f} train={res['train_sec']:.0f}s")


@app.local_entrypoint()
def main_many(categories: str, recipes: str = "light", seeds: str = "1,2", min_epochs: int = 70):
    """Same experiment for many categories at once (extras come from the mounted /extra/<cat>)."""
    with open(SOURCES_FILE, encoding="utf-8") as f:
        allsrc = json.load(f)
    jobs = [(c, r, int(sd), True, allsrc[c], min_epochs)
            for c in categories.split(",") for r in recipes.split(",") for sd in seeds.split(",")]
    print(f"{len(jobs)} runs: {len(categories.split(','))} categories x {recipes} x seeds {seeds}, min_epochs={min_epochs}")
    for j, res in zip(jobs, train_variant.starmap(jobs, return_exceptions=True)):
        if isinstance(res, Exception):
            print(f"{j[0]:13s} {j[1]} s{j[2]} FAILED {type(res).__name__}: {str(res)[:200]}")
        else:
            print(f"{res['run']:36s} train_imgs={res['train']:4d} mAP50={res['map50']:.3f} mAP50-95={res['map50_95']:.3f} train={res['train_sec']:.0f}s")
