"""Fresh COCO-initialized detector for the independent partial-pose pilot.

All framework caches and labels live in a copied training view. Formal data is
read-only. Original train and val only; original test is never staged here.
"""
from __future__ import annotations

import argparse
from collections import Counter
import json
import os
from pathlib import Path
import time

from .cluster_targets import digest, protected_snapshot
from .pose_dataset import PROJECT, protected_write, read_rows, safe_path, write_json


def stage_detector(formal, output):
    formal,output=Path(formal).resolve(),Path(output).resolve()
    if formal==output or output.is_relative_to(formal) or formal.is_relative_to(output):
        raise ValueError('Detector view must be independent from the formal dataset')
    source=read_rows(formal/'frames.jsonl')
    selected=[r for r in source if r['split'] in ('train','val')]
    groups={split:{r['group_id'] for r in selected if r['split']==split} for split in ('train','val')}
    if groups['train']&groups['val']:
        raise ValueError('Detector train/validation groups overlap')
    records=[]
    for r in selected:
        for key in ('image','yolo_label'):
            relative=r[key]
            raw=safe_path(formal,relative).read_bytes()
            import hashlib
            if hashlib.sha256(raw).hexdigest()!=r['files'][relative]:
                raise ValueError(f'Formal detector asset changed: {relative}')
            protected_write(safe_path(output,relative),raw)
        records.append({k:r[k] for k in ('frame_id','group_id','split','source_anchor_hash','image','yolo_label')})
    write_json(output/'data.json',{'path':str(output),'train':'images/train','val':'images/val',
        'names':{0:'pallet'},'nc':1})
    # YOLO expects a YAML path; JSON is valid YAML but its loader checks suffix.
    protected_write(output/'data.yaml',json.dumps({'path':str(output),'train':'images/train',
        'val':'images/val','names':{0:'pallet'},'nc':1},ensure_ascii=False,indent=2).encode())
    write_json(output/'view_manifest.json',{'records':records,'counts':dict(Counter(r['split'] for r in records)),
        'source_dataset':str(formal),'source_index_sha256':digest(formal/'frames.jsonl'),
        'source_manifest_sha256':digest(formal/'manifest.json'),'test_staged':False,
        'view_uses_copies_not_mutable_hardlinks':True})
    return records


def train(config_path):
    config_path=Path(config_path).resolve()
    config=json.loads(config_path.read_text())
    out=PROJECT/config['output'];out.mkdir(parents=True,exist_ok=True)
    d=config['detector']
    if os.environ.get('CUDA_VISIBLE_DEVICES','').lower()!=d['gpu_uuid'].lower():
        raise ValueError('Set CUDA_VISIBLE_DEVICES to the configured full GPU UUID before import')
    import torch
    from .devices import pinned_cuda_metadata
    metadata=pinned_cuda_metadata(d['gpu_uuid'])
    formal=Path(json.loads((PROJECT/config['formal_config']).read_text())['dataset'])
    weights=PROJECT/d['weights']
    protected=protected_snapshot(formal)
    binding={'config_sha256':digest(config_path),'source_code_sha256':digest(__file__),
        'formal_index_sha256':digest(formal/'frames.jsonl'),'formal_manifest_sha256':digest(formal/'manifest.json'),
        'initial_weights_sha256':digest(weights),'device':metadata}
    manifest={'binding':binding,'protected_formal_files':protected,
        'initialization':'official_COCO_weights_not_historical_pallet_checkpoints',
        'train_split':'original_formal_train','selection_split':'original_formal_val',
        'test_used_for_selection':False,'recipe':'bounded_20_epoch_partial_pose_pilot_not_formal_baseline'}
    write_json(out/'detector_run.json',manifest)
    complete=out/'detector_completed.json'
    if complete.exists():
        record=json.loads(complete.read_text())
        if digest(record['best'])!=record['best_sha256']:raise ValueError('Completed detector checkpoint changed')
        print(json.dumps(record));return
    view=out/'detector_view'
    records=stage_detector(formal,view)
    from ultralytics import YOLO
    from ultralytics.utils import SETTINGS
    SETTINGS.update({'wandb':False,'mlflow':False,'comet':False,'tensorboard':False,'clearml':False})
    run=out/'detector'
    last=run/'weights/last.pt'
    started=time.monotonic()
    model=YOLO(str(last if last.exists() else weights))
    kwargs=dict(data=str(view/'data.yaml'),epochs=d['epochs'],imgsz=d['imgsz'],batch=d['batch'],
        workers=d['workers'],device=0,project=str(out),name='detector',exist_ok=True,
        optimizer='AdamW',lr0=d['lr0'],lrf=.01,weight_decay=.0005,nbs=16,
        warmup_epochs=3,patience=50,seed=config['seed'],deterministic=True,
        amp=True,plots=False,save=True,save_period=-1,cache=False,
        mosaic=0.,mixup=0.,cutmix=0.,copy_paste=0.,degrees=0.,shear=0.,perspective=0.,
        hsv_h=0.,hsv_s=0.,hsv_v=.1,translate=.05,scale=.2,fliplr=.5,flipud=0.,
        close_mosaic=0,cos_lr=True,val=True,verbose=False)
    model.train(resume=True) if last.exists() else model.train(**kwargs)
    best=run/'weights/best.pt'
    if not best.exists():raise ValueError('Training did not produce best.pt')
    if protected_snapshot(formal)!=protected:raise ValueError('Formal labels changed during training')
    record={'state':'complete','best':str(best),'best_sha256':digest(best),'last':str(last),
        'initial_weights_sha256':binding['initial_weights_sha256'],
        'counts':dict(Counter(r['split'] for r in records)),'gpu':metadata,
        'seconds_this_invocation':time.monotonic()-started,
        'metrics_csv':str(run/'results.csv'),'test_used_for_selection':False,
        'protected_formal_files_unchanged':len(protected),
        'recipe':'bounded_20_epoch_partial_pose_pilot_not_formal_baseline',
        'torch_version':torch.__version__}
    write_json(complete,record)
    print(json.dumps(record),flush=True)


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--config',type=Path,default=PROJECT/'configs/pallet_pose_training_v1.json')
    args=parser.parse_args();train(args.config)


if __name__=='__main__':main()
