"""Add Heuristic A check at the START of _classify_except, before BOUNDARY_CONVERSION."""
from __future__ import annotations
from pathlib import Path

p = Path("scripts/audit_exception_handling.py")
content = p.read_text(encoding="utf-8")

needle = "  # ----- Classification logic -----\n\n  # 1. ErrorInfo conversion = canonical boundary pattern\n  if creates_errorinfo:\n   return (\n    \"BOUNDARY_CONVERSION\","

replacement = """  # ----- Classification logic -----

  # 0. Heuristic A: Result-returning recovery — the canonical data-oriented pattern.
  # If the except body returns `Result(data=..., errors=[ErrorInfo(...)])`,
  # the function is following the convention. Classify as INTERNAL_COMPLIANT
  # BEFORE the BOUNDARY_CONVERSION check (which also fires for ErrorInfo creation).
  if self._returns_result(body):
   return (
    "INTERNAL_COMPLIANT",
    "Compliant: `try: ...; except: return Result(data=..., errors=[...])` is the canonical Result-recovery pattern. The convention requires Result[T] for try/except sites that can fail; this pattern satisfies the requirement. The function-name-not-ending-in-`_result` is a smell (rename to `xxx_result`); the pattern itself is compliant. (per result_migration_small_files_20260617 Phase 11.2, Heuristic A)",
   )

  # 1. ErrorInfo conversion = canonical boundary pattern
  if creates_errorinfo:
   return (
    "BOUNDARY_CONVERSION","""

if needle not in content:
    print("ERROR: needle not found")
    raise SystemExit(1)
content = content.replace(needle, replacement)
p.write_text(content, encoding="utf-8", newline="")
print("ok")
