#!/usr/bin/env python3
"""Test that qubo_solve.py correctly uses the existing quantum operators."""
import sys
import json
from pathlib import Path

REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / "scripts"))
from qubo_solve import solve_qubo_dwave, solve_qubo_ibm

def test_operators_integration():
    """Test that both operators are correctly invoked."""
    # Small toy QUBO
    qubo = {
        "n": 6,
        "linear": {str(i): 0.0 for i in range(6)},
        "quadratic": {f"{i},{j}": -1.0 for i in range(6) for j in range(i+1, 6)}
    }

    print("Testing D-Wave operator integration...")
    dwave_result = solve_qubo_dwave(qubo, seed=0, sweeps=100, num_reads=1)
    print(f"✅ D-Wave path complete")
    print(f"   Sampler: {dwave_result['sampler']}")
    print(f"   Energy: {dwave_result['energy']:.2f}")
    print(f"   Has operator_receipt: {'operator_receipt' in dwave_result}")

    # Verify operator receipt structure
    assert "operator_receipt" in dwave_result, "Missing operator_receipt"
    op_receipt = dwave_result["operator_receipt"]
    assert op_receipt["schema"] == "qubo_dwave:v1", "Wrong schema"
    assert "solver" in op_receipt, "Missing solver info"
    assert "results" in op_receipt, "Missing results"

    print("\nTesting IBM operator integration...")
    ibm_result = solve_qubo_ibm(qubo, seed=0, reps=1, num_reads=1)
    print(f"✅ IBM path complete")
    print(f"   Sampler: {ibm_result['sampler']}")
    print(f"   Energy: {ibm_result['energy']:.2f}")

    # Check that samplers are different
    assert dwave_result["sampler"] != ibm_result["sampler"], \
        f"Samplers should differ: {dwave_result['sampler']} vs {ibm_result['sampler']}"

    # Check that D-Wave uses operator (should have "simulated_annealing" from DWaveOperator)
    assert "annealing" in dwave_result["sampler"].lower() or "hybrid" in dwave_result["sampler"].lower(), \
        f"D-Wave sampler should be from operator: {dwave_result['sampler']}"

    # Check that IBM uses QAOA or fallback
    assert "qaoa" in ibm_result["sampler"].lower() or "neal" in ibm_result["sampler"].lower(), \
        f"IBM sampler should be QAOA or neal fallback: {ibm_result['sampler']}"

    print("\n✅ All operator integration tests passed!")
    print(f"\nSummary:")
    print(f"  D-Wave: {dwave_result['sampler']}")
    print(f"  IBM: {ibm_result['sampler']}")
    print(f"  Both use existing operators: ✅")

if __name__ == "__main__":
    test_operators_integration()
