"""Open the P600 sample, fly to a target height and export the result.

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

from flarelive_client import connect

PROJECT = Path(__file__).with_name("p600-gen2.fll")
OUTPUT = Path(__file__).with_name("p600-output")
DURATION = 2.0  # simulated seconds
TARGET_HEIGHT = 1.0  # meters, world Z

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

    # 1. Open the prepared scene and make temporary trial settings.
    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)
    fixed_input = ws.find_scene_object("p600/core/px4/New Object")
    ws.set_property(fixed_input, "enabled", False)  # Python supplies the command.
    ws.initialize_simulation()

    # 2. Resolve handles in the initialized world and set a position command.
    controller = ws.find_scene_object("p600/core/px4")
    sensor = ws.find_scene_object("p600/core/info")
    command = [
        0,  # position-control mode
        0, 0, TARGET_HEIGHT,  # target world position, meters
        math.nan, math.nan, math.nan,  # unspecified velocity
        math.nan, math.nan, math.nan,  # unspecified acceleration
        0, math.nan,  # yaw, unspecified yaw rate
    ]
    sample = ws.exchange_simulation_io(outputs=[sensor])
    ws.export_simulation()

    # 3. Apply the command, advance about 20 ms and record body position.
    with (OUTPUT / "trajectory.csv").open("w", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        writer.writerow(["time_s", "x_m", "y_m", "z_m"])
        while sample.simulated_time + 0.5 * sample.time_step < DURATION:
            sample = ws.exchange_simulation_io(
                inputs=[{"object": controller, "values": command}],
                outputs=[sensor],
                until_time=min(sample.simulated_time + 0.02, DURATION),
            )
            writer.writerow([sample.simulated_time, *sample.outputs[0].values[:3]])

    # 4. Export the final Cameras and return to the unmodified Document.
    ws.export_simulation(sample.simulated_steps)
    print(f"Finished at {sample.simulated_time:.4f} s; results: {OUTPUT}")
    ws.clear_simulation()
    ws.end_experiment()
