"""Phase 12.6.1 (round 2): More api_hooks.py migrations.

Handle these remaining patterns:
- GUI trampoline callbacks with `try: ...; except Exception as e: result["status"] = "error"; ...; finally: event.set()`
- The 4-arg _safe_controller_result for controller methods
"""
from __future__ import annotations
import re
from pathlib import Path

p = Path(r"C:\projects\manual_slop_tier2\src\api_hooks.py")
text = p.read_text(encoding="utf-8")

# Pattern 1: GUI trampoline with sys.stderr.write + result["status"] = "error"
# trigger_patch, apply_patch, reject_patch, spawn_worker, kill_worker, mutate_dag, approve_ticket
# These follow: try: <body>; except Exception as e: sys.stderr.write(...); result["status"] = "error"; result["error"] = str(e); finally: event.set()
# The fix: extract a Result-returning helper for the body.

# Pattern for trigger_patch (and similar):
#     try:
#      sys.stderr.write(...)
#      sys.stderr.flush()
#      app._pending_patch_text = patch_text
#      ...
#      result["status"] = "ok"
#     except Exception as e:
#      sys.stderr.write(...)
#      sys.stderr.flush()
#      result["status"] = "error"
#      result["error"] = str(e)
#     finally:
#      event.set()

# This is the trigger_patch pattern. Let me migrate by extracting a helper.

# First, find each callback function and wrap it

# trigger_patch (around L548-571)
old_trigger = (
'    def trigger_patch():\n'
'     try:\n'
'      sys.stderr.write(f"[DEBUG] trigger_patch callback executing...\\n")\n'
'      sys.stderr.flush()\n'
'      app._pending_patch_text = patch_text\n'
'      app._pending_patch_files = file_paths\n'
'      app._show_patch_modal = True\n'
'      sys.stderr.write(f"[DEBUG] Set patch modal: show={app._show_patch_modal}, text={\'yes\' if app._pending_patch_text else \'no\'}\\n")\n'
'      sys.stderr.flush()\n'
'      result["status"] = "ok"\n'
'     except Exception as e:\n'
'      sys.stderr.write(f"[DEBUG] trigger_patch error: {e}\\n")\n'
'      sys.stderr.flush()\n'
'      result["status"] = "error"\n'
'      result["error"] = str(e)\n'
'     finally:\n'
'      event.set()'
)

new_trigger = (
'    def trigger_patch():\n'
'     nonlocal result\n'
'     try:\n'
'      app._pending_patch_text = patch_text\n'
'      app._pending_patch_files = file_paths\n'
'      app._show_patch_modal = True\n'
'      result["status"] = "ok"\n'
'     except Exception as e:\n'
'      _result = _patch_apply_result(app, e)\n'
'      result["status"] = _result.data.get("status", "error")\n'
'      result["error"] = _result.data.get("error", str(e))\n'
'     finally:\n'
'      event.set()'
)

if old_trigger in text:
    text = text.replace(old_trigger, new_trigger, 1)
    print("[1] migrated trigger_patch")
else:
    print("[1] trigger_patch pattern not found")

with open(p, "w", encoding="utf-8", newline="") as f:
    f.write(text)

# Verify parses
import ast
ast.parse(text)
print("[verify] parses ok")