#!/usr/bin/env python3
"""Pure plan consistency and adversarial checks. No DB or network."""
import copy, hashlib, json
from pathlib import Path
R=Path(__file__).resolve().parent
raw=(R/"half-tie-probe-proposal.json").read_bytes()
P=json.loads(raw)
CHECKS=0
def ck(ok,msg):
    global CHECKS
    CHECKS+=1
    if not ok: raise AssertionError(msg)
def verify(p):
    ck(p["actual_execution"]=={"DB_connections":0,"SQL":0,"DDL":0,"DML":0,"business_HTTP":0},"No claimed execution")
    ck(len(p["inputs"])==24 and len(p["modes"])==2,"Exact input/mode coverage")
    c=p["new_connection_contract"]["B"]
    ck(c["real_loader_constants"]["TP_ENV"]=="local" and c["effective_nonsecret_verified"]==
       {"charset":"utf8","hostport":"3306","params_keys":[],"has_initSQL":False},"Real effective App configuration")
    for lane,s in p["lanes"].items():
        ck(s["max_live_rows"]==2 and s["budget"]["DML_attempts"]==56 and s["budget"]["DDL"]==2 and s["budget"]["transactions"]==52 and s["budget"]["rollbacks"]==52,"Exact new budget")
        ck(s["budget"]["probe_query_attempt_cap"]==360 and s["budget"]["natural_query_attempt_cap"]==24,"Read caps")
        ck(len(s["point_cases"])==48 and len(s["aggregate_cases"])==4,"Exact cases")
        ck("cdx_nfh_261011_e2f7" in s["templates"]["create"].lower() and "cdx_nf5" not in s["templates"]["create"].lower(),"New isolated object only")
        point_expected=[(m["id"]+"-H"+str(i+1).zfill(2),v["value"],m["PDO_code"]) for m in p["modes"] for i,v in enumerate(p["inputs"])]
        for case,(key,value,code) in zip(s["point_cases"],point_expected):
            ck(case["case_id"]==key and "ROLLBACK" in case["transaction"],"Point case order/rollback")
            d=case["DML"]
            ck(d["sql"].startswith("INSERT ") and d["sql"].count("?")==len(d["bindings"])==4,"Exact four input placeholders")
            ck([b["original_value"] for b in d["bindings"]]==[1,s["marker"],value,value],"Original input duplicated, not rounded")
            ck([b["PDO_type_code"] for b in d["bindings"]]==[1,2,code,code],"Exact S/OS bind types")
            ck(all(b["transform"]=="none" for b in d["bindings"]),"No hidden host normalization")
        ops=[d for a in s["aggregate_cases"] for d in a["DML"]]
        ck(len(ops)==8 and all(d["sql"].count("?")==len(d["bindings"])==4 for d in ops),"Exact aggregate pair inserts")
        ck(len(s["natural_queries"])*2==20<=s["budget"]["natural_query_attempt_cap"],"Natural20+4 reserve")
        ck(all(q["sql"].startswith("SELECT ") for q in s["natural_queries"]),"Natural read-only")
        ck(all(not any(w in d["sql"].upper() for w in ["YDY_","UPDATE ","DELETE ","ALTER ","TRUNCATE ","DROP "]) for d in [x["DML"] for x in s["point_cases"]]+ops),"No business mutation or unexpected action")
verify(P)
baseline=CHECKS
tests=[
 ("rounded input",lambda p:p["lanes"]["B"]["point_cases"][0]["DML"]["bindings"][2].update(original_value="0.13")),
 ("PDO coercion",lambda p:p["lanes"]["C"]["point_cases"][0]["DML"]["bindings"][2].update(PDO_type_code=0)),
 ("wrong old table",lambda p:p["lanes"]["B"]["templates"].update(create=p["lanes"]["B"]["templates"]["create"].replace("cdx_nfh_261011_e2f7","cdx_nf5_261011_d9a4"))),
 ("utf8mb4 override",lambda p:p["new_connection_contract"]["B"]["effective_nonsecret_verified"].update(charset="utf8mb4")),
 ("case omitted",lambda p:p["lanes"]["B"]["point_cases"].pop()),
 ("budget widened",lambda p:p["lanes"]["C"]["budget"].update(DML_attempts=57)),
 ("natural action",lambda p:p["lanes"]["C"]["natural_queries"][0].update(sql="UPDATE YDY_NUTRITION SET POWER=0")),
 ("hidden transform",lambda p:p["lanes"]["B"]["point_cases"][0]["DML"]["bindings"][2].update(transform="round2")),
]
rejected=[]
for name,mutation in tests:
    p=copy.deepcopy(P);mutation(p)
    try:verify(p)
    except AssertionError:rejected.append(name)
    else:raise AssertionError("Mutation survived "+name)
print(json.dumps({"status":"PROPOSAL_ONLY_VERIFIED_NOT_EXECUTED","proposal_sha256":hashlib.sha256(raw).hexdigest(),
 "baseline_assertions":baseline,"negative_mutations_rejected":rejected,
 "new_DB_connections":0,"new_SQL":0},ensure_ascii=False,indent=2))
