"""Project one canonical bind set into a compiled Hybrid plan.

Parameter projection validates schema and target identity, applies values to a
new immutable program, and records whether recompilation is required. It does
not call a numerical kernel or Backend.
"""

from __future__ import annotations

import json

from cascaqit import Circuit, HybridProgram
from cascaqit.parameters.projection import project_parameter_bindings


def main() -> None:
    """Bind a rotation and inspect the projection decision."""
    circuit = Circuit(1, program_id="lesson.compiler.projection.digital")
    theta = circuit.parameter("theta", lower_bound=-1.0, upper_bound=1.0)
    circuit.rz(theta, 0)
    program = (
        HybridProgram("lesson.compiler.projection")
        .digital("rotate", circuit)
        .measure_all()
    )
    original_hash = program.stable_hash()
    manager = program.parameters
    binding = manager.bind({"theta": 0.4}, bind_id="bind.lesson.compiler")
    if binding.bind_set is None:
        raise RuntimeError([item.to_dict() for item in binding.diagnostics])
    projection = project_parameter_bindings(manager, program, binding.bind_set)
    if projection.program is None or projection.plan is None:
        raise RuntimeError([item.to_dict() for item in projection.diagnostics])

    next_binding = manager.bind({"theta": 0.6}, bind_id="bind.lesson.compiler.next")
    if next_binding.bind_set is None:
        raise RuntimeError([item.to_dict() for item in next_binding.diagnostics])
    reused = project_parameter_bindings(
        manager, program, next_binding.bind_set, previous=projection
    )
    if reused.program is None or reused.plan is None:
        raise RuntimeError([item.to_dict() for item in reused.diagnostics])

    payload = {
        "track": "compiler_engineer",
        "level": "applied",
        "lesson": "parameter_projection",
        "facts": {
            "decision": projection.decision,
            "first_argument_value": projection.program.blocks[0].arguments[0].value,
            "second_decision": reused.decision,
            "second_argument_value": reused.plan.steps[0].argument_bindings[0].value,
            "original_unchanged": original_hash == program.stable_hash(),
            "payload_bound": projection.metadata["payload_bound"],
            "bound_value": projection.bind_set.values["theta"],
            "schema_hash_matches": projection.schema_hash
            == manager.schema.stable_hash(),
            "execution_ready": projection.plan.execution_ready,
            "diagnostic_codes": [item.code for item in projection.diagnostics],
            "backend_called": projection.metadata["backend_called"],
        },
        "boundaries": {
            "hardware_execution": False,
            "cloud_execution": False,
            "network_accessed": False,
            "credentials_loaded": False,
        },
    }
    print(json.dumps(payload, sort_keys=True))


if __name__ == "__main__":
    main()
