"""对带类型的双 spin Ising model 运行 VQE。

VQE 先把 model 转为 Pauli Hamiltonian，再为每个 objective point 执行 Backend Job，
使用 SciPy 优化，并单独提交 final-sampling Job。有界 baseline 只校验当前小案例。
"""

from __future__ import annotations

import json

from cascaqit import VQE, IsingModelIR, LocalBackend, OptimizerConfig


def main() -> None:
    """使用确定性输入优化一个小型 Ising energy。"""
    model = IsingModelIR.from_terms(
        problem_id="lesson.optimization.vqe",
        spins=("q0", "q1"),
        fields={"q0": -0.8, "q1": 0.35},
        couplings={("q0", "q1"): 0.6},
        offset=0.1,
    )
    result = VQE(model, layers=1).run(
        backend=LocalBackend(seed=502),
        optimizer=OptimizerConfig(
            method="Powell", max_iterations=6, max_evaluations=8, seed=502
        ),
        initial_parameters=(0.1, 0.0, -0.2, 0.0),
        final_shots=64,
    )
    candidate = result.best_observed_candidate
    baseline = result.baseline
    assert candidate is not None and baseline is not None
    assert result.final_result is not None

    payload = {
        "track": "optimization_researcher",
        "level": "advanced",
        "lesson": "vqe_workflow",
        "facts": {
            "objective_estimator": result.metadata["objective_estimator"],
            "objective_total_shots": result.metadata["objective_total_shots"],
            "workflow_total_shots": result.metadata["workflow_total_shots"],
            "backend_executions": result.metadata["workflow_backend_execution_count"],
            "final_counts": result.final_result.counts,
            "final_probabilities": result.final_result.probabilities,
            "candidate_count": candidate.count,
            "candidate_value": candidate.objective_value,
            "baseline_bitstring": baseline.bitstring,
            "evaluations": len(result.evaluations),
            "best_energy": round(result.best_evaluation.energy, 10),
            "counts_total": sum(result.final_result.counts.values()),
            "candidate_bitstring": candidate.bitstring,
            "baseline_value": baseline.objective_value,
            "termination_reason": result.termination.reason,
        },
        "boundaries": {
            "hardware_execution": False,
            "cloud_execution": False,
            "network_accessed": False,
            "credentials_loaded": False,
        },
    }
    print(json.dumps(payload, sort_keys=True))


if __name__ == "__main__":
    main()
