"""Interpret variational output against a bounded baseline and report facts.

An expert analysis separates best objective evaluation, sampled candidate, and
classical baseline. The standard Algorithm report exposes provenance and
history, but it does not upgrade a bounded comparison into an optimality proof.
"""

from __future__ import annotations

import json

from cascaqit import QAOA, LocalBackend, OptimizerConfig, QUBOProblemIR, visualize


def main() -> None:
    """Run a small QUBO and compare distinct result facts."""
    problem = QUBOProblemIR.from_terms(
        problem_id="lesson.optimization.analysis",
        variables=("x0", "x1"),
        linear_terms={"x0": -1.0, "x1": -0.6},
        quadratic_terms={("x0", "x1"): 1.2},
        offset=0.1,
    )
    result = QAOA(problem, layers=1).run(
        backend=LocalBackend(seed=503),
        optimizer=OptimizerConfig(
            method="COBYLA", max_iterations=6, max_evaluations=5, seed=503
        ),
        initial_parameters=(0.2, -0.2),
        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
    report = visualize(result)

    payload = {
        "track": "optimization_researcher",
        "level": "expert",
        "lesson": "baseline_analysis",
        "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),
            "sampled_candidate": candidate.bitstring,
            "candidate_value": candidate.objective_value,
            "baseline_bitstring": baseline.bitstring,
            "baseline_value": baseline.objective_value,
            "optimality_claim": candidate.optimality_claim,
            "report_profile": report.profile,
            "report_section_count": len(report.sections),
        },
        "boundaries": {
            "hardware_execution": False,
            "cloud_execution": False,
            "network_accessed": False,
            "credentials_loaded": False,
        },
    }
    print(json.dumps(payload, sort_keys=True))


if __name__ == "__main__":
    main()
