#!/usr/bin/env python3
"""Compare fixed-command, P and PID on a synthetic continuous-error model.
This is NOT an ELEGOO model or firmware. Original teaching example. SPDX-License-Identifier: MIT.
"""
import argparse
import math
from common import output_dir, write_csv, write_json


def simulate(kind, steps, dt, kp, ki, kd):
    y = velocity = integral = 0.0
    rows = []
    for step in range(steps + 1):
        error = 1.0 - y
        if kind == "baseline":
            command = 1.0  # Constant input; knows the model's static equilibrium.
        elif kind == "p":
            command = kp * error
        else:
            # Derivative on measurement avoids a setpoint derivative kick.
            command = kp * error + ki * integral - kd * velocity
        command = max(-3.0, min(3.0, command))
        rows.append({"t_s": step * dt, "y": y, "u": command})
        # Fixed-step semi-implicit Euler integration of y'' = u - 0.8*y' - y.
        velocity += dt * (command - 0.8 * velocity - y)
        y += dt * velocity
        integral = max(-3.0, min(3.0, integral + dt * error))
    return rows


def metrics(rows, dt):
    outside = [i for i, row in enumerate(rows) if abs(1.0 - row["y"]) > 0.02]
    last_outside = max(outside, default=-1)
    settling = None if last_outside == len(rows) - 1 else rows[last_outside + 1]["t_s"]
    return {"overshoot_percent": max(0.0, max(row["y"] for row in rows) - 1.0) * 100,
            "settling_time_s_2percent": settling,
            "final_error": 1.0 - rows[-1]["y"],
            "integral_absolute_error": dt * sum(abs(1.0 - row["y"]) for row in rows[:-1])}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out", required=True)
    parser.add_argument("--kp", type=float, default=4.0)
    parser.add_argument("--ki", type=float, default=2.0)
    parser.add_argument("--kd", type=float, default=2.0)
    parser.add_argument("--dt", type=float, default=0.02)
    parser.add_argument("--duration", type=float, default=20.0)
    args = parser.parse_args()
    try:
        numbers = (args.kp, args.ki, args.kd, args.dt, args.duration)
        if not all(math.isfinite(x) for x in numbers):
            raise ValueError("All parameters must be finite")
        if not 0 < args.dt <= 0.05 or not 1 <= args.duration <= 120:
            raise ValueError("Require 0 < dt <= 0.05 and 1 <= duration <= 120 seconds")
        if not all(0 <= value <= 30 for value in (args.kp, args.ki, args.kd)):
            raise ValueError("Teaching gains must be within 0..30")
        if args.duration / args.dt > 100000:
            raise ValueError("Use <=100000 steps")
        steps = round(args.duration / args.dt)
        if abs(steps * args.dt - args.duration) > 1e-8:
            raise ValueError("duration must be an integer multiple of dt, with <=100000 steps")
        runs = {kind: simulate(kind, steps, args.dt, args.kp, args.ki, args.kd)
                for kind in ("baseline", "p", "pid")}
        output = []
        for i in range(steps + 1):
            row = {"t_s": i * args.dt, "target": 1.0, "source": "synthetic_model"}
            for kind in runs:
                row[kind + "_y"] = runs[kind][i]["y"]
                row[kind + "_u"] = runs[kind][i]["u"]
            output.append(row)
        out = output_dir(args.out)
        write_csv(out / "control.csv", list(output[0]), output)
        write_json(out / "summary.json", {
            "source": "synthetic_model", "model": "y'' = u - 0.8*y' - y; y(0)=y'(0)=0; target=1",
            "integrator": "fixed-step semi-implicit Euler", "dt_s": args.dt, "duration_s": args.duration,
            "command_limits": [-3, 3], "integral_limits": [-3, 3],
            "gains": {"kp": args.kp, "ki": args.ki, "kd": args.kd},
            "metrics": {kind: metrics(rows, args.dt) for kind, rows in runs.items()},
            "notes": ["P uses kp; PID uses kp/ki/kd and derivative on measurement. Baseline command is fixed at 1.",
                      "Settling means every subsequent sampled point stays within 0.02 of target until this run ends; null means not observed in this window.",
                      "Dimensionless continuous error is assumed. Three line channels do not establish this model or calibrated lateral position.",
                      "Results and gains are synthetic and must not be uploaded to the robot as firmware."]})
        print(f"Synthetic control comparison written to {out}")
    except (OSError, ValueError) as exc:
        parser.error(str(exc))


if __name__ == "__main__":
    main()
