"""Preview and guarded execution helpers for an audited local-completion run.""" import argparse import gzip import json from pathlib import Path def preview_records(records, run_id=None, database=None, field=None, product=None, current=None): current = current or {} preview = [] for record in records: if record.get("outcome") != "SUCCEEDED": continue if run_id is not None and record.get("run_id") != run_id: continue if database is not None and record.get("db") != database: continue if product is not None and record.get("product_code") != product: continue for name, change in record.get("fields", {}).items(): if field is not None and name != field: continue key = (record.get("db"), record.get("product_code"), name) live = current.get(key, change.get("after")) item = { "run_id": record.get("run_id"), "database": record.get("db"), "field": name, "product": record.get("product_code"), "before": change.get("before"), "current": live, "expected_after": change.get("after"), "target": change.get("before"), "affected_rows": 1, "status": "READY", } if live != change.get("after"): item["status"] = "CONFLICT" item["reason"] = "current != expected_after" preview.append(item) return preview def load_audit(path): opener = gzip.open if str(path).endswith(".gz") else open with opener(path, "rt", encoding="utf-8") as stream: return [json.loads(line) for line in stream if line.strip()] def main(argv=None): parser = argparse.ArgumentParser() parser.add_argument("audit") parser.add_argument("--run-id") parser.add_argument("--database") parser.add_argument("--field") parser.add_argument("--product") parser.add_argument("--output", required=True) args = parser.parse_args(argv) result = preview_records(load_audit(args.audit), args.run_id, args.database, args.field, args.product) Path(args.output).write_text(json.dumps({"preview": result}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") print(json.dumps({"rows": len(result), "conflicts": sum(r["status"] == "CONFLICT" for r in result)})) return 0 if __name__ == "__main__": raise SystemExit(main())