"""Opt-in installed-menu smoke. Real Gum, read-only index, a fake Codex binary."""
import fcntl
import json
import os
from pathlib import Path
import pty
import re
import select
import signal
import struct
import tempfile
import termios
import time
import unittest


@unittest.skipUnless(os.environ.get("KILN_MENU_SMOKE") == "1", "explicit installed-menu smoke only")
class InstalledMenuTests(unittest.TestCase):
    def run_menu(self, mode):
        with tempfile.TemporaryDirectory(prefix="kiln-menu-smoke-") as directory:
            root = Path(directory)
            bin_dir = root / "bin"
            bin_dir.mkdir()
            gum = bin_dir / "gum"
            gum.write_text('''#!/usr/bin/python3
import json,os,pathlib,sys
args=sys.argv[1:]
root=pathlib.Path(os.environ['KILN_MENU_TEST_DIR'])
header=args[args.index('--header')+1]
if header=='KILN — сайт и бот':
    marker=root/'top-menu-opened'
    print('19' if marker.exists() else '0')
    marker.touch()
elif header.startswith('Вернуться в сессию KILN'):
    options=[arg for arg in args if '|' in arg and arg!='|']
    (root/'options.json').write_text(json.dumps(options))
    if os.environ['KILN_MENU_TEST_MODE']=='inject':
        print('00000000-0000-0000-0000-000000000999')
    else:
        os.execv('/usr/bin/gum',['gum',*args])
else:
    raise SystemExit('unexpected menu')
''')
            gum.chmod(0o755)
            codex = bin_dir / "codex"
            codex.write_text('''#!/usr/bin/python3
import json,os,pathlib,sys
root=pathlib.Path(os.environ['KILN_MENU_TEST_DIR'])
(root/'codex.json').write_text(json.dumps({'cwd':os.getcwd(),'args':sys.argv[1:], 'localhost_bypass':all(h in os.environ.get('NO_PROXY','').split(',') and h in os.environ.get('no_proxy','').split(',') for h in ['localhost','127.0.0.1','::1'])}))
''')
            codex.chmod(0o755)
            environment = {**os.environ, "PATH": str(bin_dir) + ":" + os.environ.get("PATH", "/usr/bin:/bin"),
                           "TERM": "xterm-256color", "KILN_MENU_TEST_DIR": str(root), "KILN_MENU_TEST_MODE": mode}
            pid, master = pty.fork()
            if pid == 0:
                os.execvpe("bash", ["bash", "/root/.local/share/admin-menu/menus/kiln-system.sh"], environment)
            fcntl.ioctl(master, termios.TIOCSWINSZ, struct.pack("HHHH", 32, 120, 0, 0))
            output = bytearray()
            chose = advanced = False
            exited = False
            deadline = time.monotonic() + 12
            try:
                while time.monotonic() < deadline:
                    ready, _, _ = select.select([master], [], [], 0.05)
                    if ready:
                        try:
                            chunk = os.read(master, 65536)
                        except OSError:
                            chunk = b""
                        output.extend(chunk)
                    # Wait until real Gum has rendered a session, then select
                    # its first row (or cancel) using the actual terminal UI.
                    if not chose and (root / "options.json").exists():
                        if mode == "inject":
                            chose = True
                        elif re.search(rb"\d{2}\.\d{2}\.\d{4} \d{2}:\d{2}", output):
                            os.write(master, b"\x1b" if mode == "cancel" else b"\r")
                            chose = True
                    if not advanced and (b"Enter" in output or "Нажмите".encode() in output):
                        os.write(master, b"\r")
                        advanced = True
                    ended, status = os.waitpid(pid, os.WNOHANG)
                    if ended:
                        exited = True
                        self.assertEqual(os.waitstatus_to_exitcode(status), 0)
                        break
                self.assertTrue(exited, "installed menu did not return cleanly")
                options = json.loads((root / "options.json").read_text())
                result_file = root / "codex.json"
                result = json.loads(result_file.read_text()) if result_file.exists() else None
                self.assertTrue(options)
                self.assertTrue(all(any(label in option for label in ("Сайт", "Бот", "Совместный")) for option in options))
                # A valid KILN conversation can mention another project in its
                # title. Check ownership by ID/cwd, never by words in a title.
                import sqlite3
                with sqlite3.connect('file:/root/.codex/state_5.sqlite?mode=ro', uri=True) as connection:
                    scoped_ids = {row[0] for row in connection.execute(
                        "SELECT id FROM threads WHERE archived=0 AND RTRIM(cwd,'/') IN (?,?,?)",
                        ('/var/www/html/kiln','/srv/kiln-bot','/var/www/html/kiln-system'))}
                self.assertTrue(all(option.rsplit('|', 1)[1] in scoped_ids for option in options))
                self.assertTrue(all(option.rsplit('|', 1)[1] not in option.split('|', 1)[0] for option in options))
                return options, result
            finally:
                os.close(master)
                if not exited:
                    os.kill(pid, signal.SIGKILL)
                    os.waitpid(pid, 0)

    def test_selected_session_launches_exact_id_in_joint_workspace(self):
        options, result = self.run_menu("select")
        self.assertIsNotNone(result)
        self.assertEqual(result["cwd"], "/var/www/html/kiln-system")
        self.assertEqual(result["args"][0], "resume")
        self.assertIn(result["args"][1], {row.rsplit("|", 1)[1] for row in options})
        self.assertNotIn("--all", result["args"])
        self.assertEqual(result["args"][2:], ["--sandbox", "danger-full-access", "--ask-for-approval", "never", "--cd", "/var/www/html/kiln-system"])
        self.assertTrue(result["localhost_bypass"])

    def test_cancel_does_not_launch_codex(self):
        _, result = self.run_menu("cancel")
        self.assertIsNone(result)

    def test_injected_unlisted_id_does_not_launch_codex(self):
        _, result = self.run_menu("inject")
        self.assertIsNone(result)


if __name__ == "__main__":
    unittest.main()
