from __future__ import annotations

import math

from ..backends.base import Backend
from ..ir.types import Instruction

NATIVE = {"x", "sx", "rz", "cx", "measure"}


def basis_map(circuit, backend: Backend):
    """
    Return a *new* circuit where non-native ops are decomposed into {x,sx,rz,cx,measure}.

    MVP: decompose 'h' as: sx(q); rz(q, pi/2)
    Notes:
    - Decomposition is correct up to a global phase, which does not affect measurement statistics.
    - Later we can extend with rx/ry etc. using Euler-style decompositions.
    """
    from ..circuit.quantum_circuit import QuantumCircuit  # avoid circular import

    out = QuantumCircuit(circuit.n_qubits, getattr(circuit, "n_clbits", 0))

    for inst in circuit.instructions:
        name = inst.name
        qs = inst.qubits
        ps = inst.params
        cs = inst.clbits

        if name in NATIVE:
            out._instructions.append(Instruction(name, qs, ps, cs))
        elif name == "h":
            q = qs[0]
            out._instructions.append(Instruction("sx", (q,), ()))
            out._instructions.append(Instruction("rz", (q,), (math.pi / 2,)))
        else:
            # Unknown non-native; keep as-is for now (later phases will expand)
            out._instructions.append(Instruction(name, qs, ps, cs))
    return out
