# qsys/ir/from_payload.py - FINAL VERSION COMPATIBLE WITH YOUR CODE
from __future__ import annotations
from typing import Any
from qsys.circuit.quantum_circuit import QuantumCircuit


def circuit_from_payload(payload: dict[str, Any]) -> QuantumCircuit:
    circ = QuantumCircuit(n_qubits=payload["n_qubits"])

    for ins in payload["instructions"]:
        op = ins["op"]
        targets = [int(t) for t in ins["targets"]]
        params = ins["params"] or {}

        if op == "RZ":
            circ.rz(theta=params.get("theta", 0.0), q=targets[0])
        elif op == "SX":
            circ.sx(q=targets[0])
        elif op == "X":
            circ.x(q=targets[0])
        elif op == "CX":
            circ.cx(control=targets[0], target=targets[1])
        elif op == "MEASURE":
            for q in targets:
                circ.measure(q, q)

    return circ
