#!/usr/bin/env python3
"""Build deterministic stratified train/val/test links and a manifest."""
from __future__ import annotations
import argparse, csv, hashlib, random, shutil
from pathlib import Path
from PIL import Image
from voc_to_yolo import CLASSES

def sha256(p):
    h=hashlib.sha256()
    with p.open('rb') as f:
        for b in iter(lambda:f.read(1<<20), b''): h.update(b)
    return h.hexdigest()

def main():
    ap=argparse.ArgumentParser(); ap.add_argument('--images',type=Path,required=True); ap.add_argument('--labels',type=Path,required=True); ap.add_argument('--out',type=Path,required=True); ap.add_argument('--seed',type=int,default=20261027); ap.add_argument('--train',type=float,default=.70); ap.add_argument('--val',type=float,default=.15)
    a=ap.parse_args(); assert abs(a.train+a.val)<1
    files=sorted(a.images.glob('*.jpg')); assert len(files)==1800, len(files)
    rng=random.Random(a.seed); groups={c:[] for c in CLASSES}
    for p in files:
        c=p.stem.rsplit('_',1)[0]; assert c in groups, p.name; groups[c].append(p)
    rows=[]
    for split in ('train','val','test'):
        (a.out/'images'/split).mkdir(parents=True,exist_ok=True)
        (a.out/'labels'/split).mkdir(parents=True,exist_ok=True)
    for c in CLASSES:
        g=groups[c]; rng.shuffle(g); n=len(g); ntr=round(n*a.train); nv=round(n*a.val)
        for split,arr in [('train',g[:ntr]),('val',g[ntr:ntr+nv]),('test',g[ntr+nv:])]:
            for p in arr:
                q=a.out/'images'/split/p.name; q.parent.mkdir(parents=True,exist_ok=True); shutil.copy2(p,q)
                src=a.labels/(p.stem+'.xml')
                # labels are generated separately; copy YOLO txt when present
                txt=a.labels/(p.stem+'.txt'); ldest=a.out/'labels'/split/(p.stem+'.txt')
                if txt.exists(): shutil.copy2(txt,ldest)
                rows.append({'image':p.name,'class':c,'split':split,'width':Image.open(p).width,'height':Image.open(p).height,'sha256':sha256(p)})
    # Keep byte-identical images together to prevent train/test leakage.  Swap
    # one non-duplicate image when a duplicate pair straddles a split; counts
    # and per-class proportions therefore remain exact.
    byhash={}
    for r in rows: byhash.setdefault(r['sha256'],[]).append(r)
    for same in byhash.values():
        splits={r['split'] for r in same}
        if len(splits) <= 1: continue
        target=sorted(splits)[0]
        for r in same: r['split']=target
        cls=same[0]['class']
        # Rebalance each affected split by swapping with a unique image.
        counts={s:sum(r['class']==cls and r['split']==s for r in rows) for s in ('train','val','test')}
        desired={'train':round(len(groups[cls])*a.train),'val':round(len(groups[cls])*a.val)}; desired['test']=len(groups[cls])-desired['train']-desired['val']
        for s in ('train','val','test'):
            while counts[s] > desired[s]:
                cand=next(r for r in rows if r['class']==cls and r['split']==s and len(byhash[r['sha256']])==1)
                cand['split']=next(t for t in ('train','val','test') if counts[t]<desired[t]); counts[s]-=1; counts[cand['split']]+=1
    # Materialize after the leakage fix (initial files are removed by replacing
    # same-named paths in their final split; stale paths are cleaned below).
    for split in ('train','val','test'):
        for p in (a.out/'images'/split).glob('*'): p.unlink()
        for p in (a.out/'labels'/split).glob('*'): p.unlink()
    for r in rows:
        p=a.images/r['image']; split=r['split']; q=a.out/'images'/split/p.name; shutil.copy2(p,q)
        shutil.copy2(a.labels/(p.stem+'.txt'),a.out/'labels'/split/(p.stem+'.txt'))
    with (a.out/'manifest.csv').open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=rows[0].keys()); w.writeheader(); w.writerows(sorted(rows,key=lambda x:x['image']))
    print('seed',a.seed,'counts', {s:sum(r['split']==s for r in rows) for s in ('train','val','test')}, 'classes', {c:{s:sum(r['class']==c and r['split']==s for r in rows) for s in ('train','val','test')} for c in CLASSES})
if __name__=='__main__': main()
