"""
Aer Provider for local simulation.
"""
from .backend import Backend
from .job import Job, Result
import uuid

# Import the internal execution logic from qsys
try:
    from qsys.runtime.execute import execute as qsys_execute
except ImportError:
    qsys_execute = None

class StatevectorSimulator(Backend):
    """Local statevector simulator backend."""
    
    @property
    def name(self):
        return "statevector_simulator"
        
    @property
    def target(self):
        """Return a default target for the simulator."""
        try:
            from qsys.backends.base import Target
            # Simulator typically has all-to-all connectivity and standard basis
            return Target(
                n_qubits=32, # Theoretical limit for 8GB RAM approx
                basis_gates={"x", "sx", "rz", "cx", "measure", "h", "y", "z", "s", "sdg", "t", "tdg", "rx", "ry", "swap"},
                coupling_map=[] # Empty list often means all-to-all in these engines, or we can generate it
            )
        except ImportError:
            return None
        
    def run(self, circuit, shots=1024, **kwargs):
        """Run the circuit using qsys."""
        if not qsys_execute:
             raise ImportError("qsys.runtime.execute not available. Cannot run simulation.")
             
        # Extract the core qsys circuit
        if not hasattr(circuit, "_core_circuit") or not circuit._core_circuit:
             raise ValueError("Circuit has no underlying qsys circuit.")
             
        core_qc = circuit._core_circuit
        
        # Execute using qsys
        # qsys.execute returns a dict with 'counts', 'statevector', etc.
        # We disable the internal qsys transpiler for now to avoid 'backend.target' errors
        # since we are not yet passing a formal qsys.Backend object.
        res_data = qsys_execute(core_qc, shots=shots, use_transpiler=False)
        
        # Wrap in Result and Job
        result = Result(res_data)
        job_id = str(uuid.uuid4())
        return Job(self, job_id, result)

class AerProvider:
    """Provider for Aer backends."""
    
    def __init__(self):
        self._backends = {
            "statevector_simulator": StatevectorSimulator()
        }
        
    def get_backend(self, name="statevector_simulator"):
        if name not in self._backends:
            raise ValueError(f"Backend '{name}' not found.")
        return self._backends[name]

# Global instance
Aer = AerProvider()
