"""Shared orchestration for the contract reconstruction engine. This module deliberately accepts the batch's persistence-backed extractor and dossier builder as dependencies. Both the browser workflow and the JSON integration boundary therefore execute the same business flow in-process, while tests can replace either dependency without constructing HTTP calls or making network requests. """ def analyze_batch(batch_id, documents, extractor, dossier_builder, progress_callback=None, llm_client=None): """Extract document passports, assemble dossiers, and shape the API result. `extractor` owns LLM interaction and persistence of each extraction; `dossier_builder` consumes those saved passports and persists the resulting graph. Keeping the calls in this order is an invariant: grouping must never observe a partially extracted batch. The callback remains optional because small batches run synchronously, while the existing large-batch route uses it to update persistent progress. """ extraction = extractor( batch_id, llm_client=llm_client, progress_callback=progress_callback, documents=documents, ) dossier_result = dossier_builder(batch_id) if extraction.get("ok") else {"ok": False} classes = extraction.get("classes", {}) math_checks_passed = sum( 1 for result in extraction.get("results", []) if (result.get("extraction") or {}).get("math_validation", {}).get("status") == "VERIFIED" ) return { "ok": bool(extraction.get("ok")) and bool(dossier_result.get("ok")), "v3": True, "done": extraction.get("done", 0), "total": len(documents), "failed": extraction.get("failed", 0), "classes": classes, "ignored_accounting": classes.get("ignored_accounting", 0), "math_checks_passed": math_checks_passed, "dossier_count": len(dossier_result.get("dossiers", [])), "ambiguous": dossier_result.get("ambiguous", 0), "unlinked": dossier_result.get("unlinked", []), }