"""
Zena Compiler module.
"""
from typing import Union, List, Optional
from ..circuit import QuantumCircuit
from ..providers.backend import Backend

# Import qsys transpiler
try:
    from qsys.transpiler.passes import transpile as qsys_transpile
except ImportError:
    qsys_transpile = None

def transpile(circuits: Union[QuantumCircuit, List[QuantumCircuit]],
              backend: Optional[Backend] = None,
              **kwargs):
    """
    Transpile the circuit(s) for a given backend.
    
    Args:
        circuits: Circuit or list of circuits to transpile.
        backend: Backend to target (optional).
        
    Returns:
        The transpiled circuit(s).
    """
    if not qsys_transpile:
        print("Warning: qsys transpiler not found. Returning circuit(s) as is.")
        return circuits

    is_list = isinstance(circuits, list)
    if not is_list:
        circuits = [circuits]

    transpiled_circuits = []
    for qc in circuits:
        if not hasattr(qc, "_core_circuit") or not qc._core_circuit:
            transpiled_circuits.append(qc)
            continue
            
        # Call qsys transpiler on the internal core circuit
        # qsys.transpile expects (core_circuit, backend)
        # Note: In Phase 2, we passed use_transpiler=False because our Zena Backends
        # didn't have .target. To make this work, we'll need to pass the wrapped qsys backend
        # if available, or a default one.
        
        # For now, let's just use the opt1q if no backend is provided
        from qsys.transpiler.opt1q import optimize_1q
        
        core_qc = qc._core_circuit
        
        if backend:
            # If backend is provided, we try to use the full qsys transpile
            # We need to extract the underlying qsys backend from Zena backend if possible
            # Or just pass the Zena backend if it has the required properties (target, etc.)
            try:
                # We expect qsys.transpile to handle cases where backend might be None or simplified
                # but if it needs .target, we might need a fallback.
                transpiled_core = qsys_transpile(core_qc, backend, **kwargs)
            except Exception as e:
                print(f"Warning: full transpile failed ({e}). Falling back to 1q optimization.")
                transpiled_core = optimize_1q(core_qc)
        else:
            # Default optimization if no backend
            transpiled_core = optimize_1q(core_qc)
            
        # Update the Zena circuit with the transpiled core
        # In a real SDK, we'd probably return a NEW Zena circuit
        qc._core_circuit = transpiled_core
        transpiled_circuits.append(qc)

    return transpiled_circuits[0] if not is_list else transpiled_circuits
