#!/usr/bin/env python3
"""Add a 'keyboard' voice summon to puck_conduct — isolated command, no tap-routing touched."""
import sys
CF = "/home/ledger/aura-next/apps/puck_face/puck_conduct.py"
s = open(CF).read()
if "KEYBOARD summon" in s:
    print("already patched"); sys.exit(0)

kbd_fn = (
    'def kbd_ask(text: str):\n'
    '    """True when the person asks for the on-screen keyboard."""\n'
    '    import re as _re\n'
    '    return bool(_re.search(r"(keyboard|key board|let me type)", text or "", _re.I))\n'
    '\n\n'
)
if "def menu_signal(which: str) -> None:" not in s:
    print("ANCHOR-NOT-FOUND: menu_signal"); sys.exit(1)
s = s.replace("def menu_signal(which: str) -> None:",
              kbd_fn + "def menu_signal(which: str) -> None:", 1)

lines = s.split("\n")
out, i, done = [], 0, False
while i < len(lines):
    out.append(lines[i])
    if (not done) and "[conduct-lite] MENU {_mn0.upper()} from" in lines[i]:
        # measure the base indent from the enclosing `if _mn0:` just above
        base = None
        for k in range(i, max(i - 10, -1), -1):
            st = lines[k].lstrip()
            if st.startswith("if _mn0:"):
                base = len(lines[k]) - len(st); break
        if base is None:
            base = len(lines[i]) - len(lines[i].lstrip()) - 4
        B = " " * base
        blk = [
            "",
            B + 'if kbd_ask(text or ""):',
            B + "    import subprocess as _kbd_sp",
            B + "    try:",
            B + '        _kbd_sp.Popen(["/usr/bin/python3", "/home/ledger/aura_face/puck_kbd_app.py"])',
            B + "    except Exception as _kbd_e:",
            B + '        log(f"[conduct-lite] KEYBOARD launch failed ({_kbd_e!r})")',
            B + '    log(f"[conduct-lite] KEYBOARD summon from {spk} {text[:40]!r}")',
            B + "    last_answer_at, last_answer_to = time.time(), spk",
            B + "    continue",
        ]
        j = i + 1
        while j < len(lines) and lines[j].strip() != "continue":
            out.append(lines[j]); j += 1
        if j < len(lines):
            out.append(lines[j])          # the menu block's continue
            out.extend(blk)
            i = j + 1; done = True; continue
    i += 1
open(CF, "w").write("\n".join(out))
print("patched" if done else "ANCHOR-NOT-FOUND: menu continue")
