# tests/test_solution_sql_parameterize.py
import json, os, subprocess
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SOL = os.path.join(ROOT, "domains", "security", "solutions", "sql-parameterize")
SOLVE = os.path.join(SOL, "solve.py")
ART = json.load(open(os.path.join(SOL, "cells", "S4-kb-spaceids-sqli.json"), encoding="utf-8"))
FIND = ART["finding"]
EXPECT = ART["expect_suggestion_contains"]
CORPUS = os.path.join(ROOT, "domains", "security", "corpus", ART["cell"])

def _run(finding, content):
    p = subprocess.run(["python3", SOLVE], input=json.dumps({"finding": finding, "file_content": content}),
                       capture_output=True, text=True)
    assert p.returncode == 0, p.stderr
    return json.loads(p.stdout)

def _read(name):
    with open(os.path.join(CORPUS, name), encoding="utf-8") as f:
        return f.read()

def test_vuln_emits_SPECIFIC_inarray_suggestion():
    r = _run(FIND, _read("vuln.ts"))
    assert r is not None and r["rung"] == "located-suggestion" and r["status"] == "ok" and r["patch"] is None
    assert EXPECT in r["suggestion"]                   # concrete shape from the artifact, NOT generic advice

def test_safe_abstains_idempotent():
    assert _run(FIND, _read("safe.ts")) is None        # already parameterized → no resolution

def test_nonmatching_class_abstains():
    assert _run({**FIND, "class": "S1"}, _read("vuln.ts")) is None      # consume, don't re-detect

def test_absent_symbol_abstains():
    assert _run({**FIND, "symbol": "noSuchFunction"}, _read("vuln.ts")) is None
