"""Open the KOI sample and drive its joints with phase-shifted sine inputs.

Install flarelive-client and start Flare Live before running this script.
Save existing work first: the script opens koi-gen2.fll in that instance.
"""
import csv
import math
from pathlib import Path

from flarelive_client import connect

PROJECT = Path(__file__).with_name("koi-gen2.fll")
OUTPUT = Path(__file__).with_name("koi-output")
DURATION = 2.0  # simulated seconds
AMPLITUDE = 0.15  # fraction of each servo model's maximum angle
FREQUENCY = 1.0  # Hz
PHASE_LAG = math.radians(60)
SERVO_PATHS = [
    "head/spine/servo",
    "head/spine/spine01/servo",
    "head/spine/spine01/spine02/servo",
    "head/spine/spine01/spine02/spine03/servo",
    "head/spine/spine01/spine02/spine03/tail_start/servo",
]

OUTPUT.mkdir(exist_ok=True)
with connect() as client:
    ws = client.workspace

    # 1. Prepare a temporary trial of the supplied fish.
    ws.open_world(PROJECT)
    ws.begin_experiment()
    ws.set_property(ws.world_handle(), "working_directory", str(OUTPUT.resolve()))
    ws.set_property(ws.world_handle(), "export.export_camera_views", True)
    for obj in ws.list_objects():
        if obj.class_name == "simexp.common.custom_input":
            ws.set_property(obj.handle, "enabled", False)
    ws.initialize_simulation()

    # 2. Resolve initialized servos and body/joint sensors.
    servos = [ws.find_scene_object(path) for path in SERVO_PATHS]
    sensors = [obj.handle for obj in ws.list_objects() if obj.class_name in (
        "simexp.rigid_bodies.body_info", "simexp.rigid_bodies.joint_sensor")]
    paths = [ws.object_details(sensor).path for sensor in sensors]
    sample = ws.exchange_simulation_io(outputs=sensors)
    ws.export_simulation()

    # 3. Ramp up the sine motion over 0.5 s, then keep its amplitude steady.
    with (OUTPUT / "trajectory.csv").open("w", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        writer.writerow(["time_s", "sensor_path", "values"])
        while sample.simulated_time + 0.5 * sample.time_step < DURATION:
            t = sample.simulated_time
            ramp = 0.5 - 0.5 * math.cos(math.pi * min(t / 0.5, 1.0))
            sample = ws.exchange_simulation_io(
                inputs=[{"object": servo, "values": [AMPLITUDE * ramp * math.sin(
                    2 * math.pi * FREQUENCY * t - i * PHASE_LAG)]}
                    for i, servo in enumerate(servos)],
                outputs=sensors,
                until_time=min(t + 0.02, DURATION),
            )
            for path, output in zip(paths, sample.outputs):
                writer.writerow([sample.simulated_time, path, " ".join(map(str, output.values))])

    # 4. Export the final Cameras; leave Simulation paused for inspection.
    ws.export_simulation(sample.simulated_steps)
    print(f"Finished at {sample.simulated_time:.4f} s; results: {OUTPUT}")
    # After inspection, Stop simulation and End experiment to return to Document.
