#!/usr/bin/env python3
"""Offline extraction only; original input/storage is never rounded or rewritten."""
import hashlib, json
from pathlib import Path

root = Path(__file__).resolve().parent
plan_bytes = (root / "probe-plan.json").read_bytes()
assert hashlib.sha256(plan_bytes).hexdigest() == "68124d2e3fdafa943e70c8c4a4f0b4e0c4dfb67098bb67df8615d7d1da41fc94"
plan = json.loads(plan_bytes)
files = {"B": root / "private-evidence/recovered-execute-B.jsonl",
         "C": root / "private-evidence/final-resumed-C.jsonl"}
out = {"classification": "ACTUAL_ISOLATED_STORAGE_ONLY_NO_BUSINESS_HTTP", "lanes": {}}
for lane, path in files.items():
    if not path.exists():
        continue
    raw = path.read_bytes()
    events = [json.loads(line) for line in raw.splitlines()]
    spec = plan["lanes"][lane]["five_float_group"]
    steps = {case["case_id"]: case for case in spec["steps"]}
    actual = {}
    current = None
    for e in events:
        event, data = e["event"], e["data"]
        if event == "case-start":
            current = data["case_id"]
            actual[current] = {"reads": {}, "DML": [], "warnings": []}
        elif event in ("DML-success", "DML-failure", "DML-start") and current:
            actual[current]["DML"].append({"event": event, **data})
        elif event == "warnings" and current and data["role"] != "zero_seed_insert":
            actual[current]["warnings"] = data["rows"]
        elif event == "read-success" and current:
            for name in ["native", "text", "decimal30"]:
                if data["sql"] == spec["statements"][name]:
                    actual[current]["reads"][name] = data
    records = []
    for case_id, state in actual.items():
        st = steps[case_id]
        op = [x for x in st["DML"] if x["role"] != "zero_seed_insert"][0]
        input_start = [x for x in state["DML"] if x["event"] == "DML-start" and x["role"] != "zero_seed_insert"][0]
        mode, operation = case_id.split("-")[0], case_id.split("-")[-1]
        params = input_start["parameters"]
        bi = 2 if operation == "INSERT" else 0
        for col, original in op["column_original_values"].items():
            binding = None
            if original is not None or mode in ["S", "N"]:
                binding = params[bi]
                bi += 1
            native = state["reads"].get("native", {})
            text = state["reads"].get("text", {})
            decimal = state["reads"].get("decimal30", {})
            nk = col.lower()
            val = lambda r, key: r.get("rows", [{}])[0].get(key) if r.get("rows") else None
            typed = native.get("typed_rows", [{}])[0].get(nk, {}) if native.get("typed_rows") else {}
            records.append({
                "case_id": case_id, "column": col, "original_lexeme": original,
                "binding": "SQL NULL literal" if binding is None else binding,
                "native_value": val(native, nk), "native_type": typed.get("php_type"),
                "native_float17g": typed.get("float17g"), "native_double_hex": typed.get("native_double_hex"),
                "server_text": val(text, nk + "_text"), "server_decimal30": val(decimal, nk + "_decimal30"),
                "warnings": state["warnings"] if lane == "B" else None,
            })
    complete = [e["data"] for e in events if e["event"] == "complete"]
    out["lanes"][lane] = {
        "raw_sha256": hashlib.sha256(raw).hexdigest(),
        "complete": complete[-1] if complete else None,
        "case_count": len(actual), "value_record_count": len(records), "records": records,
        "DML_errors": [e["data"] for e in events if e["event"] == "DML-failure"],
        "warning_collection_status": "SHOW_WARNINGS_collected_after_all72_DML" if lane == "B" else "unknown_no_proven_equivalent_warning_API",
        "input_DML_warning_count": sum(bool(x["warnings"]) for x in actual.values()) if lane == "B" else None,
        "warning_row_count": sum(len(x["warnings"]) for x in actual.values()) if lane == "B" else None,
    }
if set(out["lanes"]) == {"B", "C"}:
    b = {(x["case_id"], x["column"]): x for x in out["lanes"]["B"]["records"]}
    c = {(x["case_id"], x["column"]): x for x in out["lanes"]["C"]["records"]}
    assert b.keys() == c.keys()
    pairs = []
    for k in b:
        B, C = b[k], c[k]
        assert B["original_lexeme"] == C["original_lexeme"] and B["binding"] == C["binding"]
        pairs.append({"case_id": k[0], "column": k[1], "original_lexeme": B["original_lexeme"],
                      "native_value_equal": B["native_value"] == C["native_value"],
                      "native_type_equal": B["native_type"] == C["native_type"],
                      "server_text_equal": B["server_text"] == C["server_text"],
                      "decimal30_equal": B["server_decimal30"] == C["server_decimal30"]})
    out["comparison"] = {"paired_values": len(pairs),
                         "native_value_differences": sum(not x["native_value_equal"] for x in pairs),
                         "native_type_differences": sum(not x["native_type_equal"] for x in pairs),
                         "server_text_differences": sum(not x["server_text_equal"] for x in pairs),
                         "decimal30_differences": sum(not x["decimal30_equal"] for x in pairs),
                         "pairs": pairs}
print(json.dumps(out, ensure_ascii=False, separators=(",", ":")))
