from pathlib import Path

import numpy as np

from uipc import Engine, Scene, World, builtin, view
from uipc.backend import BufferView
from uipc.constitution import Particle
from uipc.diff_sim import AdjointMethodFeature, EnableGradFeature, UpdateParameterFeature
from uipc.geometry import label_surface, pointcloud


def host_buffer(values):
    assert values.ndim == 1 and values.flags.c_contiguous
    return BufferView(values.ctypes.data, 0, values.size, values.itemsize,
                      values.itemsize, builtin.none)


workspace = Path("output/docs/native_adjoint_python")
workspace.mkdir(parents=True, exist_ok=True)
engine = Engine("cuda", str(workspace))
world = World(engine)
cfg = Scene.default_config()
cfg["dt"] = 0.02
cfg["gravity"] = [[0.0], [0.0], [0.0]]
cfg["contact"]["enable"] = False
cfg["newton"]["semi_implicit"]["enable"] = 0
cfg["newton"]["velocity_tol"] = 1e-10
cfg["newton"]["velocity_tol_relative"] = 0.0
cfg["linear_system"]["tol_rate"] = 1e-12
scene = Scene(cfg)
parameters = scene.diff_sim().parameters()
parameters.resize(1)
view(parameters)[:] = [0.2]

mesh = pointcloud(np.zeros((1, 3)))
label_surface(mesh)
Particle().apply_to(mesh, 1000.0, 0.001)
mesh.vertices().create("mass", 1.0)
mesh.vertices().create("diff/velocity", np.array([0, -1, -1], dtype=np.int32))
slot, _ = scene.objects().create("particle").geometries().create(mesh)
world.init(scene)
if not world.is_valid() or not world.dump():
    raise RuntimeError("Could not initialize and save frame zero")

recording = world.features().find(EnableGradFeature)
update = world.features().find(UpdateParameterFeature)
adjoint = world.features().find(AdjointMethodFeature)
assert all(feature is not None for feature in (recording, update, adjoint))
if not world.recover(0):
    raise RuntimeError("Could not restore frame zero")
physical = np.array([0.5], dtype=np.float64)
update.update(host_buffer(physical))
offset = int(view(slot.geometry().meta().find(builtin.dof_offset)).item())
recording.with_grad()
try:
    for frame in (1, 2):
        world.advance()
        assert world.is_valid() and world.frame() == frame and engine.frame_stats()["converged"]
        indices = np.array([offset] if frame == 2 else [], dtype=np.int32)
        adjoint.select_dofs(frame, host_buffer(indices))
finally:
    recording.no_grad()

output = np.empty(1, dtype=np.float64)
adjoint.receive_dofs(host_buffer(output))
seed = output - 0.07  # dL/dy for L = (y - 0.07)^2 / 2
gradient = np.empty(1, dtype=np.float64)
adjoint.compute_dLdP(host_buffer(gradient), host_buffer(seed))
print(f"x = {output[0]:.8f}, dL/dP = {gradient[0]:.8f}")
np.testing.assert_allclose([output[0], gradient[0]], [0.02, -0.002], rtol=0, atol=1e-10)
