"""Runs a tour of the SDK fully offline. Use it to check an installation:  python run_all_offline.py"""

import math

import quantakit
from quantakit import QuantumCircuit, Parameter, transpile, LocalSimulator
from quantakit.circuit import library
from quantakit.primitives import Sampler, Estimator
from quantakit.quantum_info import Statevector, SparsePauliOp, partial_trace
from quantakit.visualization import text_histogram
from quantakit import qasm3

print(f"QuantaKit {quantakit.__version__} (Book Edition {quantakit.BOOK_EDITION})\n")

# 1. A Bell pair
qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0, 1)
print(qc.draw(), "\n")
print("State:", Statevector(qc))

qc.measure_all()
counts = Sampler().run([qc], shots=1000, seed=7).result()[0].data.meas.get_counts()
print(text_histogram(counts), "\n")

# 2. Parameters and the Estimator
theta = Parameter("θ")
ry = QuantumCircuit(1)
ry.ry(theta, 0)
for value in (0, math.pi / 3, math.pi / 2, math.pi):
    ev = Estimator().run([(ry, SparsePauliOp("Z"), [value])]).result()[0].data.evs
    print(f"<Z> at theta = {value:.3f}: {ev:+.3f}")
print()

# 3. Entanglement seen through the reduced state
rho = partial_trace(Statevector(library.bell_state()), [1])
print("Purity of one qubit of a Bell pair:", round(rho.purity(), 3), "\n")

# 4. Grover search for 101
grover = library.grover(3, ["101"])
counts = Sampler().run([grover], shots=1000, seed=1).result()[0].data.meas.get_counts()
print(text_histogram(counts, sort="value", top=4), "\n")

# 5. Transpile to a hardware basis
hw = transpile(library.qft(3), basis_gates=["rz", "sx", "x", "cx"], optimization_level=2)
print("QFT(3) on rz/sx/x/cx:", hw.count_ops(), "depth", hw.depth(), "\n")

# 6. OpenQASM 3
print(qasm3.dumps(library.bell_state()))
print("All examples ran offline on", LocalSimulator())
