"""cine-25 demo: teach an agent to land Gymnasium's LunarLander-v3 with PPO (Stable-Baselines3), on a CPU, and record
real episodes along the way. Everything the reel shows of the lander's flights comes from here.

    python train.py OUT_DIR [TOTAL_STEPS]

PPO settings: the RL Baselines3 Zoo's tuned LunarLander-v2/v3 hyperparameters (n_envs 16, n_steps 1024, batch 64,
4 epochs, gamma 0.999, gae_lambda 0.98, ent_coef 0.01). Checkpoints at 0 (untrained), 100k, 300k and the end: each
is scored on 20 episodes (fixed seeds 1000-1019) and one episode (seed 1007) is recorded frame by frame with its
per-step state, action and reward.
"""
import csv, json, os, sys, time
import numpy as np
import torch
import gymnasium as gym
from PIL import Image
from stable_baselines3 import PPO
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.callbacks import BaseCallback

OUT = sys.argv[1]
TOTAL = int(sys.argv[2]) if len(sys.argv) > 2 else 1_000_000
os.makedirs(OUT, exist_ok=True)
torch.set_num_threads(8)
CHECKS = [0, 100_000, 300_000, TOTAL]
SEEDS = list(range(1000, 1020))
REC_SEED = 1007
log = open(os.path.join(OUT, "train_log.txt"), "w")


def say(*a):
    s = " ".join(str(x) for x in a); print(s, flush=True); log.write(s + "\n"); log.flush()


def evaluate(model, tag):
    env = gym.make("LunarLander-v3")
    scores, outcomes = [], []
    for sd in SEEDS:
        obs, _ = env.reset(seed=sd)
        tot, done = 0.0, False
        while not done:
            a = env.action_space.sample() if model is None else int(model.predict(obs, deterministic=True)[0])
            obs, r, term, trunc, _ = env.step(a)
            tot += r; done = term or trunc
        scores.append(tot)
        outcomes.append("landed" if (term and r > 50) else ("crashed" if (term and r < -50) else ("timeout" if trunc else "other")))
    env.close()
    # one episode, recorded: frames + per-step data
    env = gym.make("LunarLander-v3", render_mode="rgb_array")
    d = os.path.join(OUT, "rollouts", tag); os.makedirs(d, exist_ok=True)
    obs, _ = env.reset(seed=REC_SEED)
    rows, tot, done, i = [], 0.0, False, 0
    rng = np.random.default_rng(REC_SEED)
    while not done:
        if model is None:
            a = int(rng.integers(4))
        else:
            a = int(model.predict(obs, deterministic=True)[0])
        frame = env.render()
        Image.fromarray(frame).save(os.path.join(d, f"{i:05d}.png"))
        obs2, r, term, trunc, _ = env.step(a)
        rows.append([i, *[float(v) for v in obs], a, float(r), tot + r])
        tot += r; obs = obs2; done = term or trunc; i += 1
    Image.fromarray(env.render()).save(os.path.join(d, f"{i:05d}.png"))
    env.close()
    with open(os.path.join(d, "steps.csv"), "w", newline="") as f:
        csv.writer(f).writerows([["step", "x", "y", "vx", "vy", "angle", "vang", "leg_l", "leg_r", "action", "reward", "total"]] + rows)
    res = {"tag": tag, "mean": float(np.mean(scores)), "std": float(np.std(scores)), "scores": [round(s, 1) for s in scores],
           "landed": outcomes.count("landed"), "crashed": outcomes.count("crashed"), "timeout": outcomes.count("timeout"),
           "recorded_seed": REC_SEED, "recorded_total": round(tot, 1), "recorded_steps": i}
    say(f"[{tag}] mean {res['mean']:.1f} +- {res['std']:.1f} over 20 | landed {res['landed']} crashed {res['crashed']} "
        f"timeout {res['timeout']} | recorded episode: {tot:.1f} in {i} steps")
    return res


class Checkpoints(BaseCallback):
    def __init__(self):
        super().__init__()
        self.results, self.curve, self.t0 = [], [], time.time()

    def _on_step(self):
        for info in self.locals.get("infos", []):
            if "episode" in info:
                self.curve.append((self.num_timesteps, float(info["episode"]["r"])))
        for c in CHECKS[1:-1]:
            if self.num_timesteps >= c and not any(r["tag"] == f"{c // 1000}k" for r in self.results):
                say(f"checkpoint {c} at {time.time() - self.t0:.0f} s")
                self.results.append(evaluate(self.model, f"{c // 1000}k"))
        return True


t0 = time.time()
venv = make_vec_env("LunarLander-v3", n_envs=16, seed=0)
model = PPO("MlpPolicy", venv, n_steps=1024, batch_size=64, n_epochs=4, gamma=0.999, gae_lambda=0.98, ent_coef=0.01,
            verbose=0, seed=0, device="cpu")
results = [evaluate(None, "0k")]
cb = Checkpoints()
model.learn(total_timesteps=TOTAL, callback=cb)
results += cb.results
say(f"trained {TOTAL} steps in {time.time() - t0:.0f} s")
results.append(evaluate(model, f"{TOTAL // 1000}k"))
model.save(os.path.join(OUT, "ppo_lunarlander"))
with open(os.path.join(OUT, "curve.csv"), "w", newline="") as f:
    csv.writer(f).writerows([["timesteps", "episode_reward"]] + cb.curve)
json.dump({"total_steps": TOTAL, "seconds": round(time.time() - t0), "results": results,
           "hyper": {"n_envs": 16, "n_steps": 1024, "batch_size": 64, "n_epochs": 4, "gamma": 0.999, "gae_lambda": 0.98,
                     "ent_coef": 0.01}}, open(os.path.join(OUT, "result.json"), "w"), indent=1)
say("done")
