"""Compare paired-electron QPE and BQPE with and without BEAST-VQE preparation."""
# ruff: noqa # ruff: ignore[noqa-comments]

# snippet-start: module-imports
from pathlib import Path

import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator

import qrunch as qc

# snippet-end: module-imports


# snippet-start: plot-energies
def plot_energies(
    beast_energies: list[float],
    phase_estimation_energies: dict[str, float],
    *,
    outdir: Path = Path("dist"),
    show: bool = False,
) -> None:
    """
    Plot BEAST-VQE convergence alongside the four phase estimation results.

    Args:
        beast_energies: Total energies including the initial and final BEAST-VQE energies.
        phase_estimation_energies: Labels and total energies of the QPE and BQPE runs.
        outdir: Directory in which to save the comparison plot.
        show: Whether to display the plot interactively.

    """
    outdir.mkdir(parents=True, exist_ok=True)
    figure, axes = plt.subplots()
    axes.plot(range(len(beast_energies)), beast_energies, "-*", color="darkgreen", label="BEAST-VQE")
    for (label, energy), color, linestyle in zip(
        phase_estimation_energies.items(),
        ("royalblue", "orange", "firebrick", "purple"),
        ("-", "--", "-.", ":"),
        strict=True,
    ):
        axes.axhline(energy, color=color, linestyle=linestyle, label=label)

    axes.set_xlabel("BEAST-VQE iteration (including initial and final energies)")
    axes.set_ylabel("Total energy [Hartree]")
    axes.set_title("LiH: paired-electron phase estimation")
    # Display only integer x-axis ticks.
    axes.xaxis.set_major_locator(MaxNLocator(integer=True))
    axes.legend()
    figure.tight_layout()
    figure.savefig(outdir / "qpe_from_beast.png", dpi=200, bbox_inches="tight")
    if show:
        plt.show()
    plt.close(figure)


# snippet-end: plot-energies


def main(*, outdir: Path = Path("dist"), show: bool = True) -> tuple[list[float], dict[str, float]]:
    """
    Run the LiH comparison using cuQuantum statevector simulation.

    Args:
        outdir: Directory in which to save the comparison plot.
        show: Whether to display the plot interactively.

    Basic QPE uses twelve precision qubits and 300 fixed Trotter steps per evolution.
    BQPE uses dynamic stepping with a 300-step cap and may stop before reaching
    its requested tolerance of 0.001 Hartree. These encoders do not target the
    same leading-order Trotter error budget. Converge their step counts
    independently before interpreting the energy comparison.

    """
    # snippet-start: molecular-problem
    molecular_configuration = qc.build_molecular_configuration(
        molecule=[
            ("H", 0.0, 0.0, 0.0),
            ("Li", 1.5474, 0.0, 0.0),
        ],
        basis_set="sto3g",
    )
    problem_builder = qc.problem_builder_creator().ground_state().standard().create()
    problem = problem_builder.build_restricted(molecular_configuration)
    # snippet-end: molecular-problem

    # snippet-start: cuquantum-components
    sampler = (
        qc
        .sampler_creator()
        .cuquantum_statevector()
        .with_options(qc.options.CuQuantumStatevectorSamplerOptions(float_type="f32"))
        .create()
    )
    estimator = (
        qc
        .estimator_creator()
        .cuquantum_statevector()
        .with_options(qc.options.CuQuantumStatevectorEstimatorOptions(float_type="f32"))
        .create()
    )
    # snippet-end: cuquantum-components

    # snippet-start: beast-preparation
    beast_calculator = (
        qc
        .calculator_creator()
        .vqe()
        .iterative()
        .beast()
        .with_estimator(estimator)
        .with_options(qc.options.IterativeVqeOptions(max_iterations=20))
        .choose_minimizer()
        .quick_default()
        .create()
    )
    beast_result = beast_calculator.calculate(problem)
    # snippet-end: beast-preparation

    # snippet-start: hamiltonian-encoder
    max_trotter_steps = 300
    hamiltonian_encoder = (
        qc
        .hamiltonian_encoder_creator()
        .trotterization()
        .suzuki_trotter()
        .with_expansion_order(2)
        .with_options(
            qc.options.TrotterizationHamiltonianEncoderOptions(mode="fixed_steps", trotter_steps=max_trotter_steps)
        )
        .create()
    )
    # snippet-end: hamiltonian-encoder

    # snippet-start: basic-qpe-calculator
    qpe_calculator = (
        qc
        .calculator_creator()
        .quantum_phase_estimation()
        .basic()
        .paired_electron_approximation()
        .with_sampler(sampler)
        .with_options(qc.options.BasicQuantumPhaseEstimationOptions(number_of_precision_qubits=12))
        .with_hamiltonian_encoder(hamiltonian_encoder)
        .create()
    )
    # snippet-end: basic-qpe-calculator

    # snippet-start: basic-qpe-calculations
    qpe_result = qpe_calculator.calculate(problem)
    qpe_from_beast_result = qpe_calculator.calculate(problem, beast_result)
    # snippet-end: basic-qpe-calculations

    # snippet-start: bayesian-qpe-encoder
    hamiltonian_encoder = (
        qc
        .hamiltonian_encoder_creator()
        .trotterization()
        .suzuki_trotter()
        .with_expansion_order(2)
        .with_options(
            qc.options.TrotterizationHamiltonianEncoderOptions(
                mode="dynamic_steps", trotter_steps=20, reference_time=1.0, max_trotter_steps=max_trotter_steps
            )
        )
        .create()
    )
    # snippet-end: bayesian-qpe-encoder

    # snippet-start: bayesian-qpe-calculator
    bqpe_calculator = (
        qc
        .calculator_creator()
        .quantum_phase_estimation()
        .bayesian()
        .paired_electron_approximation()
        .with_estimator(estimator)
        .with_options(
            qc.options.BayesianQuantumPhaseEstimationOptions(
                convergence_rate=5.0,
                tolerance=1.0e-3,
                max_number_of_iterations=100,
            )
        )
        .with_hamiltonian_encoder(hamiltonian_encoder)
        .create()
    )
    # snippet-end: bayesian-qpe-calculator

    # snippet-start: bayesian-qpe-calculations
    bqpe_result = bqpe_calculator.calculate(problem)
    bqpe_from_beast_result = bqpe_calculator.calculate(problem, beast_result)
    # snippet-end: bayesian-qpe-calculations

    # snippet-start: compare-energies
    beast_energies = beast_result.total_energy_per_macro_iteration_with_initial_energy_and_final_energy.values
    phase_estimation_energies = {
        "QPE from Hartree-Fock": qpe_result.total_energy.value,
        "QPE from BEAST-VQE": qpe_from_beast_result.total_energy.value,
        "BQPE from Hartree-Fock": bqpe_result.total_energy.value,
        "BQPE from BEAST-VQE": bqpe_from_beast_result.total_energy.value,
    }
    plot_energies(
        beast_energies,
        phase_estimation_energies,
        outdir=outdir,
        show=show,
    )
    # snippet-end: compare-energies
    return beast_energies, phase_estimation_energies


if __name__ == "__main__":
    main()
