"""Build a Brizo scene from URDF, drive its joints and export Camera images.

Install flarelive-client, place your brizo_urdf package beside this script and
start Flare Live. Save existing work first: this script creates a new Document.
"""
import csv
import math
from pathlib import Path

from flarelive_client import connect

URDF = Path(__file__).with_name("brizo_urdf")
OUTPUT = Path(__file__).with_name("brizo-output")
DURATION = 2.0  # simulated seconds; increase for a longer swimming trial
FREQUENCY = 1.0  # Hz
AMPLITUDES = [8, 12, 18]  # degrees, from head to tail
PHASE_LAG = math.radians(60)
MAX_ANGLE = math.radians(30)  # shared servo model limit


def set_properties(ws, obj, values):
    """Apply a group of property values to one object."""
    for path, value in values.items():
        ws.set_property(obj, path, value)


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

    # 1. Import the robot into a new Document and place its free-base instance.
    ws.new_world()
    with ws.transaction("Build Brizo scene"):
        asset, = ws.run_action("rigid-bodies.import-robot", files=[str(URDF.resolve())]).objects
        ws.set_property(asset, "fixed_base", False)
        root, = ws.instantiate_preset(asset)
        ws.set_property(root, "name", "Brizo")
        world = ws.world_handle()
        set_properties(ws, world, {
            "working_directory": str(OUTPUT.resolve()),
            "gravity.z": 0.0,
            "export.export_camera_views": True,
            "export.camera_view_width": 960,
            "export.camera_view_height": 640,
        })

        # 2. Configure water and couple the robot's visual triangle meshes.
        # New documents already contain the rigid-body and Gen 2 solvers.
        fluid = next(obj.handle for obj in ws.list_objects()
                     if obj.class_name == "simexp.blocks_fluid.gen2.solver")
        set_properties(ws, fluid, {
            "fluid.initial_density": 1000.0,
            "fluid.kinematic_shear_viscosity": 1e-6,
            "fluid.resolution": 0.01,
            "fluid.max_velocity": 2.0,
            "boundary.wall_model.model": 1,  # CappedNavierSlip
            "boundary.wall_model.maximum_slip_ratio": 0.8,  # Brizo tutorial setting
            "visualization.velocity_range_max": 0.35,
            "visualization.opacity_scale": 0.25,
        })
        for obj in ws.list_objects():
            if obj.class_name == "simexp.common.geometry.shapes.triangle_mesh":
                flags = {label: value for value, label in
                         ws.property_metadata(obj.handle, "use_as").enum_options}
                role = ws.get_property(obj.handle, "use_as")
                if role & flags["Visual"]:
                    ws.set_property(obj.handle, "use_as", role | flags["FluidBoundary"])

        # 3. Keep X/Y translation and yaw free; lock Z, roll and pitch.
        ws.set_property(root, "limit_joint_movement", True)
        for dof in ("angular_x", "angular_y", "linear_z"):
            for group in ("position", "velocity"):
                for side in ("lower", "upper"):
                    ws.set_property(root, f"joint_{group}_{side}_limits.{dof}", 0.0)

        # 4. Add a shared servo model, three drives and joint-angle sensors.
        model = ws.create_object("simexp.uav.simple_servo_model")
        set_properties(ws, model, {
            "name": "Brizo servo model",
            "max_angle": MAX_ANGLE,
            "max_torque": 1.0,
            "max_angular_velocity": math.radians(360),
            "controller_kp": 30.0,
            "controller_ki": 0.0,
            "controller_kd": 0.05,
        })
        joints = {obj.name: obj.handle for obj in ws.list_objects()
                  if obj.class_name == "simexp.rigid_bodies.revolute_joint_body_pair"}
        joint_paths = []
        for name in ("link1", "link2", "lin3"):  # names in the supplied URDF
            joint = joints[name]
            joint_paths.append(ws.object_details(joint).path)
            servo = ws.create_object("simexp.uav.simple_servo", parent=joint)
            set_properties(ws, servo, {"name": "Servo", "model": model})
            sensor = ws.create_object("simexp.rigid_bodies.joint_sensor", parent=joint)
            set_properties(ws, sensor, {"name": "Angle", "mode": 0})  # Position
        info = ws.create_object("simexp.rigid_bodies.body_info", parent=root)
        ws.set_property(info, "name", "Motion")

        # 5. Add tracked side/top Cameras for image export.
        for name, position, rotation in (
            ("Brizo side", (1.15, 0.18, 0.25), (0, -0.13, 0)),
            ("Brizo top", (0, 0.2, 1.15), (0, -math.pi / 2, 0)),
        ):
            camera = ws.create_object("simexp.core.camera")
            set_properties(ws, camera, {"name": name, "vertical_fov": 40.0})
            for group, vector in (("position", position), ("rotation", rotation)):
                for axis, value in zip("xyz", vector):
                    ws.set_property(camera, f"{group}.{axis}", value)
            tracker = ws.create_object("simexp.common.position_tracker", parent=camera)
            ws.set_property(tracker, "target", root)
            for axis, value in zip("xyz", position):
                ws.set_property(tracker, f"offset_on_target.{axis}", value)

    # 6. Initialize, then resolve handles in the Simulation world.
    ws.initialize_simulation()
    servos = [ws.find_scene_object(path + "/Servo") for path in joint_paths]
    sensors = [ws.find_scene_object(path + "/Angle") for path in joint_paths]
    info = ws.find_scene_object("Brizo/Motion")
    sample = ws.exchange_simulation_io(outputs=[*sensors, info])
    ws.export_simulation()

    # 7. Send sine targets, advance about 20 ms and record measured motion.
    with (OUTPUT / "trajectory.csv").open("w", newline="", encoding="utf-8") as file:
        writer = csv.writer(file)
        writer.writerow(["time_s", "target_link1_deg", "target_link2_deg", "target_lin3_deg",
                         "actual_link1_deg", "actual_link2_deg", "actual_lin3_deg",
                         "x_m", "y_m", "z_m"])
        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))
            angles = [math.radians(a) * ramp * math.sin(2 * math.pi * FREQUENCY * t - i * PHASE_LAG)
                      for i, a in enumerate(AMPLITUDES)]
            sample = ws.exchange_simulation_io(
                inputs=[{"object": servo, "values": [angle / MAX_ANGLE]}
                        for servo, angle in zip(servos, angles)],
                outputs=[*sensors, info],
                until_time=min(t + 0.02, DURATION),
            )
            measured = [math.degrees(output.values[0]) for output in sample.outputs[:3]]
            writer.writerow([sample.simulated_time, *map(math.degrees, angles),
                             *measured, *sample.outputs[3].values[:3]])

    # 8. Export final images; leave Simulation paused for inspection.
    ws.export_simulation(sample.simulated_steps)
    print(f"Finished at {sample.simulated_time:.4f} s; results: {OUTPUT}")
    # Stop simulation to return to the configured Document, then save it as FLL.
