
# ── Core ─────────────────────────────────────────────────────────
from .quantum import QuantumCircuit
from .parameters import Parameter, ParameterVector
from .primitives import SamplerV2, EstimatorV2, SamplerResult, EstimatorResult

# ── Gates ─────────────────────────────────────────────────────────
from .gates import h, x, y, z, s, sdg, t, tdg, rx, ry, rz, cnot, cz, cy, swap, toffoli

# ── Backends ──────────────────────────────────────────────────────
from .backend import StatevectorSimulator, StabilizerSimulator, MPS_Simulator, execute, BackendV2
from .simulator import AerSimulator, DensityMatrixSimulator

# ── Noise ─────────────────────────────────────────────────────────
from .noise import NoiseModel, DepolarizingError, AmplitudeDampingError
from .noise import PauliError, PhaseDampingError, ThermalRelaxationError
from .noise_v2 import (BitFlipError, PhaseFlipError,
    DepolarizingError as DepolarizingErrorV2,
    AmplitudeDampingError as AmplitudeDampingErrorV2,
    PhaseDampingError as PhaseDampingErrorV2,
    NoiseModel as NoiseModelV2)

# ── Measurement ───────────────────────────────────────────────────
from .measurement import ClassicalRegister, measure_all, measure_partial, measure_qubit

# ── Transpiler ────────────────────────────────────────────────────
from .transpiler_v2 import (PassManager, UnrollToffoliPass,
    MergeRotationsPass, CancelInversePass, BasisTranslationPass)

# ── Qiskit Compatibility ──────────────────────────────────────────
from .qiskit_compat_v2 import to_qasm, from_qasm, to_qiskit, from_qiskit

# ── Fast Gate Math ────────────────────────────────────────────────
from .fast_statevector import (apply_1q, apply_2q, apply_3q,
    rx_mat, ry_mat, rz_mat, u1_mat, u2_mat, u3_mat)

# ── Algorithms (original) ─────────────────────────────────────────
from .algorithms import (quantum_flip, super_quantum_dance, quantum_treasure_hunt,
    quantum_magic_spin, bb84_qkd, grover_search, qft, phase_estimation,
    shor_period_finding, vqe, qaoa, hhl)

# ── Algorithms v2 (fixed & new) ───────────────────────────────────
from .algorithms_v2 import (grover, quantum_phase_estimation, amplitude_amplification)

__version__ = "2.3.1"

# ── v2.3.2 : AI Quantum Assistant ────────────────────────────────
try:
    from .ai_assistant import generate_circuit, explain_circuit
except Exception as _e:
    print(f"[PKTron] ai_assistant not loaded: {_e}")

# ── v2.3.2 : Step-by-Step Simulator ─────────────────────────────
try:
    from .step_simulator import run_step_by_step, print_steps, plot_steps
except Exception as _e:
    print(f"[PKTron] step_simulator not loaded: {_e}")

# ── v2.3.2 : Quantum Debugger ────────────────────────────────────
try:
    from .quantum_debugger import QuantumDebugger
except Exception as _e:
    print(f"[PKTron] quantum_debugger not loaded: {_e}")

from .profiler import PerformanceProfiler, ProfileResult

from .hhl import (hhl_solve, HHLResult, variational_qls, QLSResult, quantum_conjugate_gradient, randomised_kaczmarz)

from .qpca import (qpca_fit, QPCAResult, incremental_qpca, quantum_kernel_pca, QKernelPCAResult, quantum_randomised_svd)

from .shor_full import shor_factor, ShorResult, build_qft_matrix, build_inverse_qft_matrix

# ── Quantum GAN ──────────────────────────────────────────────────
try:
    from .qgan import QGAN, QGANResult, plot_qgan
except Exception as _e:
    print(f"[PKTron] qgan not loaded: {_e}")

# ── Quantum Walks ────────────────────────────────────────────────
try:
    from .quantum_walk import (QuantumWalk, DiscreteQuantumWalk,
        ContinuousQuantumWalk, QuantumWalkResult, build_graph,
        hitting_time_analysis, plot_walk, plot_walk_animation)
except Exception as _e:
    print(f"[PKTron] quantum_walk not loaded: {_e}")

# ── Advanced Algorithms (v2.3.2+) ────────────────────────────────────────────
try:
    from .advanced_algorithms import (
        AdvancedQuantum,
        grover_search, build_oracle, amplitude_amplification,
        run_qaoa, build_qaoa_circuit, optimize_qaoa,
        run_vqe, run_adapt_vqe, run_sampling_vqe,
        qpe, iterative_qpe, hamiltonian_qpe,
        amplitude_estimation, iterative_amplitude_estimation, mle_amplitude_estimation,
        trotter_evolution, varqrte, varqite,
        build_qnn, train_qnn, quantum_kernel, quantum_kernel_matrix,
        qft, inverse_qft,
        basis_encoding, amplitude_encoding, angle_encoding,
        parameter_shift_gradient, optimize_parameters, variational_loop,
    )
except Exception as _e:
    print(f"[PKTron] advanced_algorithms not loaded: {_e}")

# ── Phase 7: Advanced VQE / Hamil-Sim / Block Encoding / Enhanced QPE ────────
try:
    from .advanced_algorithms import (
        run_he_vqe, run_hi_vqe, run_spsa_vqe,
        run_adapt_vqe_plus, spsa_optimize,
        suzuki_trotter2, qdrift,
        qubitization_walk_eigenphases,
        landau_zener_dynamics, tully_surface_hopping,
        block_encode_dense, fable_block_encode,
        lcu_block_encode, qsvt_apply, pauli_decompose,
        textbook_qpe, iterative_qpe, hadamard_test_qpe,
        robust_qpe, scaled_qpe_large,
        HamiltonianPhaseEstimation,
    )
except Exception as _e:
    print(f"[PKTron] Phase 7 not loaded: {_e}")

# ── Quantum Finance (PKTron v2.3.2+) ─────────────────────────────────────
from .finance.qaoa_portfolio    import build_portfolio_qaoa, optimize_portfolio
from .finance.vqe_portfolio     import create_ansatz, cost_function, run_vqe_portfolio
from .finance.quantum_monte_carlo import (simulate_returns, estimate_var,
                                          amplitude_estimation,
                                          price_european_option)
from .finance.fraud_detection   import build_vqc, train_vqc, predict_transaction
from .finance.grover_search     import build_oracle, run_grover_search
from .finance.qkd_bb84          import generate_key, simulate_channel, detect_eavesdropping
from .finance.api               import QuantumFinance

# ── Scientific Domains (PKTron Scientific Extension) ─────────────────────
from . import physics
from . import chemistry
from . import biology
from . import cosmology
from . import space
from . import algorithms_science
try:
    from . import crypto    # pktron/crypto/ (may need prior cells run)
except Exception:
    pass


# ── Plot Histogram Fix ────────────────────────────────────────────
try:
    from .visualization import plot_histogram
except Exception:
    import numpy as np
    import matplotlib.pyplot as plt

    def plot_histogram(circuit, shots=1024):
        from .backend import StatevectorSimulator, execute
        backend = StatevectorSimulator()
        result = execute(circuit, backend, shots=shots)
        counts = result.get_counts()
        n = circuit.num_qubits
        states = [f"|{i:0{n}b}>" for i in range(min(2**n, 64))]
        probs  = [counts.get(f"{i:0{n}b}", 0)/shots for i in range(min(2**n, 64))]
        fig, ax = plt.subplots(figsize=(10, 5))
        ax.bar(states, probs, color="steelblue")
        ax.set_xlabel("State")
        ax.set_ylabel("Probability")
        ax.set_title("PKTron Quantum Histogram")
        plt.xticks(rotation=45, ha="right")
        plt.tight_layout()
        plt.show()
        return counts

# GPU Simulators
try:
    from .gpu import GPUStatevectorSimulator, GPUDensityMatrixSimulator
except Exception as _e:
    print(f"[PKTron] GPU simulators not loaded: {_e}")
