from pathlib import Path
p=Path('C:/Solutions/foster/hermes-agent/gateway/platforms/webhook.py')
s=p.read_text(encoding='utf-8')
old='''import json
import logging
import re
import subprocess
import time
from collections import deque
from typing import Any, Deque, Dict, List, Optional
'''
new='''import json
import logging
import os
import re
import subprocess
import tempfile
import time
from collections import deque
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Deque, Dict, List, Optional
'''
if old in s: s=s.replace(old,new,1)
elif 'from datetime import datetime, timezone' not in s: raise SystemExit('import anchor not found')
old2='''        delivery = self._delivery_info.get(chat_id, {})
        deliver_type = delivery.get("deliver", "log")

        if deliver_type == "log":
'''
new2='''        delivery = self._delivery_info.get(chat_id, {})
        deliver_type = delivery.get("deliver", "log")

        # Persist actual ask-michel responses for Foster polling. The final
        # send occurs after any interim status sends and therefore wins.
        if chat_id.startswith("webhook:ask-michel:"):
            payload = delivery.get("payload", {})
            request_id = str(payload.get("request_id", ""))
            if re.fullmatch(r"[A-Za-z0-9._-]{6,128}", request_id):
                results_dir = Path("C:/MCSJAgent/foster-ask-michel/results")
                results_dir.mkdir(parents=True, exist_ok=True)
                result = {
                    "request_id": request_id,
                    "status": "completed",
                    "completed_at": datetime.now(timezone.utc).isoformat(),
                    "answer": content,
                    "confidence": "high",
                    "proof": [],
                    "caveats": [],
                }
                destination = results_dir / f"{request_id}.json"
                fd, temporary = tempfile.mkstemp(prefix=destination.name + ".", suffix=".tmp", dir=results_dir)
                try:
                    with os.fdopen(fd, "w", encoding="utf-8", newline="\\n") as handle:
                        json.dump(result, handle, ensure_ascii=False, indent=2)
                        handle.write("\\n")
                        handle.flush()
                        os.fsync(handle.fileno())
                    os.replace(temporary, destination)
                finally:
                    if os.path.exists(temporary):
                        os.unlink(temporary)

        if deliver_type == "log":
'''
if old2 in s: s=s.replace(old2,new2,1)
elif 'Persist actual ask-michel responses for Foster polling' not in s: raise SystemExit('send anchor not found')
p.write_text(s,encoding='utf-8',newline='\n')
compile(s,str(p),'exec')
Path('C:/MCSJAgent/proof/ask-michel-runtime-patch.txt').write_text('PATCHED_AND_COMPILED\n',encoding='ascii')
