# tests/test_contract_resolution.py
import importlib.util, os, pytest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_spec = importlib.util.spec_from_file_location("sg_contract", os.path.join(ROOT, "prevent", "contract.py"))
contract = importlib.util.module_from_spec(_spec); _spec.loader.exec_module(contract)

LOC = {"file": "kb.ts", "line": 281, "symbol": "listArticlesBySpaceIds"}

def test_located_suggestion_ok_no_patch():
    r = contract.resolution("sql-parameterize", "S4", "located-suggestion", LOC, "use inArray(...)")
    assert r["status"] == "ok" and r["patch"] is None and r["rung"] == "located-suggestion"
    assert r["adapter"] == "sql-parameterize" and r["class"] == "S4" and r["location"] == LOC

def test_unresolved_auto_degrades():
    r = contract.resolution("a", "S4", "located-suggestion", LOC, "s", unresolved=["could not derive args"])
    assert r["status"] == "degraded" and r["coverage"]["unresolved"] == ["could not derive args"]

def test_patch_rejected_on_located_suggestion():
    with pytest.raises(ValueError):
        contract.resolution("a", "S4", "located-suggestion", LOC, "s", patch="diff")

def test_patch_rejected_when_degraded():
    with pytest.raises(ValueError):
        contract.resolution("a", "S4", "syntactic-local", LOC, "s", patch="diff", unresolved=["x"])

def test_patch_ok_on_syntactic_local():
    r = contract.resolution("a", "S4", "syntactic-local", LOC, "s", patch="diff")
    assert r["status"] == "ok" and r["patch"] == "diff"

def test_bad_rung_raises():
    with pytest.raises(ValueError):
        contract.resolution("a", "S4", "auto-magic", LOC, "s")
