#!/usr/bin/env bash
# Interactive native-window regression: synthetic SQLite only, no Keychain
# or inherited user configuration. Click once, decline, close, then session.
set -euo pipefail
cd "$(dirname "$0")/.."
source scripts/lib/isolated-test-env.sh
if [[ -z "${SEQUEL_MCP_BIN:-}" ]]; then cargo build --locked; fi
BIN="${SEQUEL_MCP_BIN:-${CARGO_TARGET_DIR:-target}/debug/sequel-mcp}"
iso_init
SERVER_PID=""
cleanup() {
  if [[ -n "$SERVER_PID" ]]; then kill "$SERVER_PID" 2>/dev/null || true; wait "$SERVER_PID" 2>/dev/null || true; fi
  rm -rf "$ISO_ROOT"
}
trap cleanup EXIT INT TERM
python3 - "$ISO_ROOT" <<'PY'
import json, sqlite3, sys
from pathlib import Path
root = Path(sys.argv[1])
db = root / 'demo.sqlite'
with sqlite3.connect(db) as conn:
    conn.execute('CREATE TABLE items (id INTEGER PRIMARY KEY, value INTEGER NOT NULL)')
    conn.execute('INSERT INTO items VALUES (1, 0)')
config = root / 'config/sequel-mcp/config.json'
config.parent.mkdir(parents=True)
config.write_text(json.dumps({'version': 2, 'revision': 1, 'defaultConnection': 'approval-demo',
    'connections': [{'driver': 'sqlite', 'name': 'approval-demo', 'path': str(db), 'database': 'main',
        'policy': {'read': 'allow', 'write': 'confirm', 'ddl': 'deny', 'admin': 'deny', 'txCtrl': 'deny',
            'maxRows': 5000, 'maxExecutionMs': 30000, 'maxBackupRows': 100, 'onBackupOverflow': 'abort', 'requireBiometric': False},
        'tablePolicies': {}}], 'retention': {}}))
config.chmod(0o600)
PY
mkfifo "$ISO_ROOT/in" "$ISO_ROOT/out"
env -i PATH="$PATH" HOME="$ISO_ROOT/home" XDG_CONFIG_HOME="$ISO_ROOT/config" \
  XDG_DATA_HOME="$ISO_ROOT/data" XDG_CACHE_HOME="$ISO_ROOT/cache" XDG_RUNTIME_DIR="$ISO_ROOT/runtime" \
  SEQUEL_MCP_TEST_MODE=1 SEQUEL_MCP_TEST_ROOT="$ISO_ROOT" SEQUEL_MCP_TEST_GUI=1 \
  "$BIN" serve <"$ISO_ROOT/in" >"$ISO_ROOT/out" 2>"$ISO_ROOT/server.log" &
SERVER_PID=$!
python3 -u - "$ISO_ROOT" "$SERVER_PID" <<'PY'
import json, os, select, sqlite3, sys, time
from pathlib import Path
root, pid = Path(sys.argv[1]), int(sys.argv[2])
writer = (root / 'in').open('w', buffering=1)
reader = os.open(root / 'out', os.O_RDONLY | os.O_NONBLOCK)
buffer, seq = b'', 0
def rpc(method, params):
    global buffer, seq
    seq += 1
    writer.write(json.dumps({'jsonrpc': '2.0', 'id': seq, 'method': method, 'params': params}) + '\n')
    deadline = time.monotonic() + 75
    while time.monotonic() < deadline:
        if not select.select([reader], [], [], 0.1)[0]: continue
        buffer += os.read(reader, 65536)
        while b'\n' in buffer:
            line, buffer = buffer.split(b'\n', 1)
            msg = json.loads(line)
            if msg.get('id') == seq:
                assert 'error' not in msg, msg
                return msg['result']
    raise TimeoutError(method)
rpc('initialize', {'protocolVersion': '2024-11-05', 'capabilities': {}, 'clientInfo': {'name': 'approval-gui-test', 'version': '1'}})
writer.write(json.dumps({'jsonrpc': '2.0', 'method': 'notifications/initialized'}) + '\n')
for label, expected in [('Approve once', 1), ('Decline', 1), ('Close window', 1), ('Approve for session', 2), ('Session reuse: no window expected', 3)]:
    print('GUI STEP: ' + label, flush=True)
    started = time.monotonic()
    result = rpc('tools/call', {'name': 'execute', 'arguments': {'connection': 'approval-demo', 'database': 'main', 'sql': 'UPDATE items SET value = value + 1 WHERE id = 1'}})
    with sqlite3.connect(root / 'demo.sqlite') as conn:
        value = conn.execute('SELECT value FROM items WHERE id = 1').fetchone()[0]
    assert value == expected, (label, value, result)
    assert bool(result.get('isError')) == (label in ('Decline', 'Close window')), result
    if label.startswith('Session reuse'):
        assert time.monotonic() - started < 5, 'session grant prompted again'
    print('PASS: ' + label + '; value=' + str(value), flush=True)
writer.close()
os.close(reader)
print('Native GUI choices and session reuse PASSED', flush=True)
PY
wait "$SERVER_PID"
SERVER_PID=""
