"""Pick the best PPO checkpoint of one run.
Usage: python select_best.py RUNS_DIR MODE SEED      (e.g. python select_best.py . random 1)
Every checkpoint gets the same 20 random start poses (joint angles nudged by up to +-0.05 rad, friction 1.0).
Score = mean of the strict "tipping forfeits" score (-1 m for a trial that tilts past 30 degrees).
These 20 SELECTION starts come from seed 5000+SEED; the final TEST in analyze.py uses different starts
(seed 100+SEED), so the winner is never graded on the trials it was picked with."""
import sys, json, glob, pickle, numpy as np, mujoco
import walker_env as W
from stable_baselines3 import PPO

N_SELECT = 20

def trial(pol, vn, rng):
    """One 5-second trial, forfeit rule. Stops early once the robot tips (the score is then -1 m anyway)."""
    env = W.WalkerEnv('forfeit'); env.reset()
    d = env.data; W.randomize_start(env.model, d, rng); obs = env._obs()
    for _ in range(W.STEPS // env.FRAME_SKIP):
        a, _ = pol.predict(vn.normalize_obs(obs), deterministic=True)
        obs, r, term, trunc, _ = env.step(a)
        if term:
            return -1.0, True
    return float(d.qpos[0]), False

def score_checkpoint(path):
    pol = PPO.load(path + '.zip', device='cpu'); vn = pickle.load(open(path + '_norm.pkl', 'rb'))
    rng = np.random.default_rng(5000 + SEED)
    res = [trial(pol, vn, rng) for _ in range(N_SELECT)]
    return dict(mean=float(np.mean([s for s, _ in res])), tipped=sum(t for _, t in res))

if __name__ == '__main__':
    RUNS, MODE, SEED = sys.argv[1], sys.argv[2], int(sys.argv[3])
    name = f'ppo_{MODE}_seed{SEED}'
    log = json.load(open(f'{RUNS}/{name}.json'))
    rows = []
    for r in log:
        s = score_checkpoint(f"{RUNS}/{name}_ck/ck{r['ck']:03d}")
        rows.append(dict(r, select_mean=s['mean'], select_tipped=s['tipped']))
        print(f"ck {r['ck']:3d}  trials {r['trials']:5d}  20 starts: mean {s['mean']:5.2f} m  tipped {s['tipped']:2d}/20", flush=True)
    best = max(rows, key=lambda r: (r['select_mean'], -r['select_tipped'], r['ck']))   # ties: fewer tips, then later
    json.dump(dict(rows=rows, best_ck=best['ck']), open(f'{RUNS}/{name}_select.json', 'w'), indent=1)
    print('best checkpoint', best['ck'], 'at', best['trials'], 'trials:', round(best['select_mean'], 2), 'm,', best['select_tipped'], '/ 20 tipped')
