"""针对小型 MIS 问题运行完整的本地 QAOA 流程。

程序完成问题投影、ansatz 构造、Backend objective evaluation、SciPy 优化、最终
采样和候选解码，并给出有界的经典比较。该比较只适用于当前小问题，不证明全局最优。
"""

from __future__ import annotations

import json

from cascaqit import QAOA, GraphProblemIR, LocalBackend, OptimizerConfig


def main() -> None:
    """使用固定输入优化并采样一个三节点路径图。"""
    graph = GraphProblemIR.from_edges(
        problem_id="lesson.optimization.qaoa",
        positions={"a": (0.0, 0.0), "b": (5.0, 0.0), "c": (10.0, 0.0)},
        edges=(("a", "b"), ("b", "c")),
    )
    result = QAOA(graph, layers=1, mis_penalty=2.0).run(
        backend=LocalBackend(seed=501),
        optimizer=OptimizerConfig(
            method="COBYLA", max_iterations=8, max_evaluations=5, seed=501
        ),
        initial_parameters=(0.2, -0.3),
        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": "applied",
        "lesson": "qaoa_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,
            "best_energy": round(result.best_evaluation.energy, 10),
            "candidate_value": candidate.objective_value,
            "termination_reason": result.termination.reason,
            "evaluations": len(result.evaluations),
            "counts_total": sum(result.final_result.counts.values()),
            "candidate_bitstring": candidate.bitstring,
            "candidate_feasible": candidate.feasible,
            "baseline_value": baseline.objective_value,
            "optimality_claim": candidate.optimality_claim,
        },
        "boundaries": {
            "hardware_execution": False,
            "cloud_execution": False,
            "network_accessed": False,
            "credentials_loaded": False,
        },
    }
    print(json.dumps(payload, sort_keys=True))


if __name__ == "__main__":
    main()
