"""用数字编译路线运行一个小型图问题。"""

from __future__ import annotations

import json

from cascaqit import MockNeutralAtomTarget
from cascaqit.problems import GraphProblemIR, ProblemCompiler, decode_graph_bitstring


def main() -> None:
    """用三节点经典参考检查采样候选解。"""
    graph = GraphProblemIR.from_edges(
        problem_id="guide.problem.path",
        positions={"a": (0.0, 0.0), "b": (6.0, 0.0), "c": (12.0, 0.0)},
        edges=(("a", "b"), ("b", "c")),
    )
    compiled = ProblemCompiler().compile(
        graph,
        mode="digital",
        algorithm="qaoa",
        target=MockNeutralAtomTarget.local_ahs_v0_1(),
        layers=1,
    )
    execution = compiled.run(
        params={"gamma_0": 0.16, "beta_0": 0.24}, shots=128, seed=508
    )
    candidates = [decode_graph_bitstring(graph, f"{i:03b}") for i in range(8)]
    optimum = max(
        item["selection_size"] for item in candidates if item["is_independent"]
    )
    counts = execution.result.counts
    feasible_counts = sum(
        count
        for bits, count in counts.items()
        if decode_graph_bitstring(graph, bits)["is_independent"]
    )
    if sum(counts.values()) != 128 or optimum != 2:
        raise RuntimeError("采样总数或经典参考结果不正确。")
    print(
        json.dumps(
            {
                "mode": "digital",
                "algorithm": "qaoa",
                "logical_order": list(execution.logical_order),
                "counts": counts,
                "counts_total": sum(counts.values()),
                "classical_maximum_size": optimum,
                "feasible_frequency": feasible_counts / 128,
                "best_observed_bitstring": execution.best_observed_candidate.bitstring,
                "best_observed_feasible": execution.best_observed_candidate.feasible,
                "objective_value": execution.objective_value,
            },
            sort_keys=True,
        )
    )


if __name__ == "__main__":
    main()
