"""Add _returns_result helper to audit_exception_handling.py."""
from __future__ import annotations
from pathlib import Path

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

needle = " def _has_simple_return(self, stmts: list[ast.stmt]) -> bool:\n  \"\"\"True if the body contains a `return <value>` statement (any value type).\"\"\"\n  for s in stmts:\n   if isinstance(s, ast.Return) and s.value is not None:\n    return True\n  return False\n\n def _uses_exception_inline(self, stmts: list[ast.stmt]) -> bool:"

replacement = """ def _has_simple_return(self, stmts: list[ast.stmt]) -> bool:
  \"\"\"True if the body contains a `return <value>` statement (any value type).\"\"\"
  for s in stmts:
   if isinstance(s, ast.Return) and s.value is not None:
    return True
  return False

 def _returns_result(self, stmts: list[ast.stmt]) -> bool:
  \"\"\"True if the body returns a `Result(...)` call (canonical Result-recovery pattern).

  Detects `return Result(data=..., errors=[...])` — the canonical
  data-oriented error handling pattern. Matches any call to `Result(...)`
  with at least a `data=` keyword argument. The pattern is compliant
  when used in a try/except: it satisfies the convention that every
  try/except site that can fail must return `Result[T]` with structured
  `ErrorInfo`. The function-name-not-ending-in-`_result` is a smell
  (the function should be renamed to `xxx_result`), but the pattern
  itself is compliant (heuristic A from Phase 11.2).
  \"\"\"
  for s in stmts:
   if not isinstance(s, ast.Return) or s.value is None:
    continue
   if not isinstance(s.value, ast.Call):
    continue
   f = s.value.func
   if isinstance(f, ast.Name) and f.id == "Result":
    return True
   if isinstance(f, ast.Attribute) and f.attr == "Result":
    return True
  return False

 def _uses_exception_inline(self, stmts: list[ast.stmt]) -> bool:"""

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")
