"""Phase 12.6.1: Migrate api_hooks.py silent-fallback sites to Result[T]."""
from __future__ import annotations
from pathlib import Path

p = Path(r"C:\projects\manual_slop_tier2\src\api_hooks.py")
with open(p, "rb") as f:
    text = f.read()

# 1. Add import for Result types (after existing imports)
import_marker = b"from src.module_loader import _require_warmed\r\n"
if import_marker not in text:
    raise SystemExit("import marker not found")

import_addition = b"from src.module_loader import _require_warmed\r\nfrom src.result_types import ErrorInfo, ErrorKind, Result\r\n"
text = text.replace(import_marker, import_addition, 1)
print("[1] Added Result imports")

# 2. Add helper function before class HookServerInstance
helper_block = (
    'def _safe_controller_result(controller: Any, method_name: str, fallback: dict) -> Result[dict]:\n'
    ' """Safely call controller.<method_name>(); return Result[dict] with fallback on error.\n'
    '\n'
    ' Per error_handling.md: log/silent-fallback sites must propagate Result[T] to a true\n'
    ' drain point. This helper internally does the try/except and returns Result[dict]\n'
    ' (matching Heuristic A: Result-returning recovery = INTERNAL_COMPLIANT). The HTTP\n'
    ' response (the drain point) terminates the propagation.\n'
    '\n'
    ' [C: src/api_hooks.py:HookHandler.do_GET, src/api_hooks.py:HookHandler.do_POST]\n'
    ' """\n'
    ' if controller is None or not hasattr(controller, method_name):\n'
    '  return Result(data=fallback, errors=[ErrorInfo(kind=ErrorKind.NOT_READY, message=f"controller missing or has no {method_name}", source=f"api_hooks._safe_controller_result.{method_name}")])\n'
    ' try:\n'
    '  data = getattr(controller, method_name)()\n'
    '  return Result(data=data if data is not None else fallback)\n'
    ' except Exception as e:\n'
    '  return Result(data=fallback, errors=[ErrorInfo(kind=ErrorKind.INTERNAL, message=str(e), source=f"api_hooks._safe_controller_result.{method_name}", original=e)])\n'
    '\n'
    '\n'
).encode()

class_marker = b"class HookServerInstance(ThreadingHTTPServer):"
if class_marker not in text:
    raise SystemExit("class HookServerInstance not found")

text = text.replace(class_marker, helper_block + class_marker, 1)
print("[2] Added _safe_controller_result helper")

# 3. Now migrate the silent-fallback sites.
import re

pattern = re.compile(
    rb'if controller and hasattr\(controller, "([^"]+)"\):\r?\n'
    rb'\s+try:\r?\n'
    rb'\s+payload = controller\.\1\(\)\r?\n'
    rb'\s+except Exception:\r?\n'
    rb'\s+payload = (\{[^}]+\})\r?\n'
    rb'\s+else:\r?\n'
    rb'\s+payload = (\{[^}]+\})',
    re.MULTILINE
)

def replace_match(m):
    method_name = m.group(1).decode()
    fallback_exc = m.group(2).decode().strip()
    fallback_else = m.group(3).decode().strip()
    fallback = fallback_exc
    replacement = f'payload = _safe_controller_result(controller, "{method_name}", {fallback}).data'.encode()
    return replacement

text, count = pattern.subn(replace_match, text)
print(f"[3] Migrated {count} silent-fallback sites")

with open(p, "wb") as f:
    f.write(text)
print(f"[done] wrote {len(text)} chars")

import ast
ast.parse(text.decode("utf-8"))
print("[verify] parses ok")