#!/usr/bin/env python3
import json, os, re, shutil, subprocess, sys

HOME = os.path.expanduser('~')
SELF = os.path.realpath(__file__)
REG = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(SELF))), 'src', 'sub-clis.json')
BASE = os.path.join(HOME, '.local', 'share', 'tm-ai')
NPM = os.path.join(BASE, 'npm')
NODE = os.path.join(BASE, 'node')
SHIM = os.path.join(BASE, 'shim')
OPENERS = ['xdg-open', 'sensible-browser', 'x-www-browser', 'www-browser', 'gnome-open', 'kde-open', 'wslview', 'open']
OLD_STUBS = ['gio', 'firefox', 'google-chrome', 'chromium', 'chromium-browser']
B, D, R = '\033[1m', '\033[2m', '\033[0m'
KEYS = os.path.join(BASE, 'keys')
ASKING = os.path.join(HOME, '.local', 'state', 'tm-ai', 'asking-key')
PASTE = re.compile(r'\x1b\[20[01]~')
KEY_OK = re.compile(r'^[A-Za-z0-9._~+/=:-]{16,512}$')
KEY_PIECE = re.compile(r'^[A-Za-z0-9._-]+$')
NOT_PIECES = {'thanks', 'thank', 'thx', 'ty', 'ok', 'okay', 'here', 'key', 'done', 'please', 'pls', 'cheers', 'hi', 'hello',
              'regards', 'best', 'bye', 'yes', 'sure'}


def say(msg=''):
    sys.stdout.write(msg + '\n')
    sys.stdout.flush()


CHILD = []
TTY = []


def run(cmd, e, cwd):
    """(exit code, was Ctrl+C pressed while it ran)"""
    p = subprocess.Popen(['bash', '-c', cmd], env=e, cwd=cwd)
    CHILD.append(p)
    hit = False
    try:
        while True:
            try:
                return p.wait(), hit
            except KeyboardInterrupt:
                hit = True
    finally:
        CHILD.remove(p)


def stop(n, _f):
    import signal, time
    sigs = (signal.SIGINT, signal.SIGHUP, signal.SIGTERM)
    try:
        try:
            for s in sigs:
                signal.signal(s, signal.SIG_IGN)
        except KeyboardInterrupt:
            for s in sigs:
                signal.signal(s, signal.SIG_IGN)
        try:
            if os.getpgrp() == os.getpid():
                os.killpg(os.getpgrp(), n)
            else:
                for p in CHILD:
                    p.send_signal(n)
        except OSError:
            pass
        end = time.time() + 2
        for p in list(CHILD):
            while time.time() < end:
                try:
                    if os.waitid(os.P_PID, p.pid, os.WEXITED | os.WNOHANG | os.WNOWAIT) is not None:
                        break
                except ChildProcessError:
                    break
                time.sleep(0.02)
        tty_back()
    finally:
        sys.exit(128 + n)


def tty_back():
    """The terminal as tm-ai found it, and the screen modes an AI may have left, back to normal for the shell."""
    try:
        import termios
        if TTY:
            termios.tcsetattr(sys.stdin.fileno(), termios.TCSANOW, TTY[0])
        os.write(sys.stdout.fileno(), b'\x1b[?25h\x1b[?2004l\x1b[<u\x1b[>4;0m')
    except Exception:
        pass


def signals_back():
    """Before the AI takes over this process: its stop signals as a fresh program gets them (never left ignored)."""
    import signal
    for s in (signal.SIGINT, signal.SIGHUP, signal.SIGTERM):
        signal.signal(s, signal.SIG_DFL)


def load():
    try:
        with open(REG, encoding='utf-8') as f:
            return {c['id']: c for c in json.load(f).get('clis', []) if isinstance(c, dict) and c.get('id')}
    except Exception as e:
        say('tm-ai: cannot read %s (%s)' % (REG, e))
        return {}


def shim():
    os.makedirs(SHIM, exist_ok=True)
    body = ('#!/bin/sh\n# tm-ai: print the link instead of opening a desktop browser\n'
            'for a in "$@"; do case "$a" in http*|file:*) u="$a";; esac; done\n'
            '[ -n "$u" ] || u="$*"\n'
            'printf "\\r\\n\\033[1mOpen this link on your phone:\\033[0m\\r\\n%s\\r\\n\\r\\n" "$u" > /dev/tty 2>/dev/null || '
            'printf "\\nOpen this link on your phone:\\n%s\\n\\n" "$u" >&2\nexit 0\n')
    for n in OLD_STUBS:
        p = os.path.join(SHIM, n)
        try:
            if os.path.isfile(p) and '# tm-ai: print the link' in open(p).read():
                os.unlink(p)
        except OSError:
            pass
    for n in OPENERS:
        p = os.path.join(SHIM, n)
        try:
            if not os.path.exists(p) or open(p).read() != body:
                with open(p, 'w') as f:
                    f.write(body)
                os.chmod(p, 0o755)
        except OSError:
            pass


def env_for(c):
    e = dict(os.environ)
    dirs = [SHIM, os.path.join(NODE, 'bin'), os.path.join(NPM, 'bin')]
    dirs += [os.path.join(HOME, d) for d in c.get('binDirs') or []]
    dirs += [os.path.join(HOME, '.local', 'bin')]
    e['PATH'] = ':'.join(dirs + [p for p in e.get('PATH', '').split(':') if p and p not in dirs])
    e['BROWSER'] = os.path.join(SHIM, 'xdg-open')
    e['TM_AI_NPM'] = NPM
    e.setdefault('TERM', 'xterm-256color')
    for k in [str(x) for x in c.get('unset') or []]:
        for n in [n for n in e if (n.startswith(k[:-1]) if k.endswith('*') else n == k)]:
            e.pop(n, None)
    for k, v in (c.get('env') or {}).items():
        e[str(k)] = os.path.expandvars(os.path.expanduser(str(v)))
    for k in ('DISPLAY', 'WAYLAND_DISPLAY'):
        e.pop(k, None)
    return e


def find(c, e):
    return shutil.which(c['bin'], path=e['PATH']) or ''


def node_major(e):
    n = shutil.which('node', path=e['PATH'])
    if not n:
        return None
    try:
        v = subprocess.run([n, '-v'], capture_output=True, text=True, timeout=10).stdout.strip()
        m = re.match(r'v(\d+)\.(\d+)', v)
        return (int(m.group(1)), int(m.group(2))) if m else None
    except Exception:
        return None


def need_ok(have, need):
    m = re.match(r'\s*>=?\s*(\d+)(?:\.(\d+))?', need or '')
    if not m:
        return have is not None
    want = (int(m.group(1)), int(m.group(2) or 0))
    return have is not None and have >= want


def get_node(need):
    """Download the newest Node LTS that satisfies `need` into ~/.local/share/tm-ai/node."""
    import hashlib, tarfile, tempfile, urllib.request
    arch = {'aarch64': 'arm64', 'arm64': 'arm64', 'x86_64': 'x64', 'amd64': 'x64'}.get(os.uname().machine)
    if not arch:
        say('tm-ai: no Node build for this computer (%s)' % os.uname().machine)
        return False
    say(D + 'Getting Node.js for it (one time)...' + R)
    with urllib.request.urlopen('https://nodejs.org/dist/index.json', timeout=30) as r:
        idx = json.load(r)
    pick = None
    for rel in idx:
        m = re.match(r'v(\d+)\.(\d+)', rel.get('version', ''))
        if rel.get('lts') and m and need_ok((int(m.group(1)), int(m.group(2))), need) and ('linux-' + arch) in rel.get('files', []):
            pick = rel['version']
            break
    if not pick:
        say('tm-ai: no Node.js release fits %s' % need)
        return False
    name = 'node-%s-linux-%s.tar.xz' % (pick, arch)
    url = 'https://nodejs.org/dist/%s/' % pick
    with urllib.request.urlopen(url + 'SHASUMS256.txt', timeout=30) as r:
        sums = r.read().decode()
    want = next((ln.split()[0] for ln in sums.splitlines() if ln.endswith('  ' + name)), '')
    os.makedirs(BASE, exist_ok=True)
    tmp = tempfile.mkdtemp(dir=BASE)
    try:
        tar = os.path.join(tmp, name)
        with urllib.request.urlopen(url + name, timeout=300) as r, open(tar, 'wb') as f:
            shutil.copyfileobj(r, f)
        if not want or hashlib.sha256(open(tar, 'rb').read()).hexdigest() != want:
            say('tm-ai: the Node.js download did not match its checksum - not used')
            return False
        with tarfile.open(tar) as t:
            t.extractall(tmp)
        src = os.path.join(tmp, name[:-len('.tar.xz')])
        if os.path.isdir(NODE):
            shutil.rmtree(NODE)
        os.rename(src, NODE)
        return True
    finally:
        shutil.rmtree(tmp, ignore_errors=True)


def install(c, e):
    say('')
    say(B + 'Setting up %s on this computer' % c['label'] + R + D + ' (one time, about a minute)' + R)
    if c.get('node'):
        if not need_ok(node_major(e), c['node']):
            try:
                if not get_node(c['node']):
                    return False
            except Exception as ex:
                say('tm-ai: could not get Node.js: %s' % ex)
                return False
    os.makedirs(NPM, exist_ok=True)
    rc, hit = run(c['install'], e, HOME)
    if hit:
        raise KeyboardInterrupt
    if rc != 0:
        say('')
        say('%s did not install (exit %d). Type: tm-ai %s   to try again.' % (c['label'], rc, c['id']))
        return False
    return bool(find(c, e))


def signed_in(c, e):
    s = c.get('signedIn') or {}
    if isinstance(s.get('files'), list) and s['files']:
        for f in s['files']:
            try:
                if os.path.isfile(os.path.join(HOME, str(f))) and os.path.getsize(os.path.join(HOME, str(f))) > 0:
                    return 'in'
            except OSError:
                pass
        return 'out'
    if not isinstance(s.get('cmd'), str) or not s['cmd']:
        return None
    try:
        r = subprocess.run(['bash', '-c', s['cmd']], env=e, cwd=HOME, stdin=subprocess.DEVNULL,
                           capture_output=True, text=True, errors='replace', timeout=30)
        t = (r.stdout or '') + (r.stderr or '')
    except Exception:
        return None
    for want, key in (('out', 'outRe'), ('in', 'inRe')):
        try:
            if s.get(key) and re.search(s[key], t, re.I):
                return want
        except re.error:
            pass
    return None


def key_path(c):
    return os.path.join(KEYS, c['id'])


def read_key(c):
    try:
        with open(key_path(c), encoding='utf-8') as f:
            k = f.read().strip()
    except (OSError, ValueError):
        return ''
    return k if KEY_OK.match(k) else ''


def save_key(c, k):
    os.makedirs(KEYS, mode=0o700, exist_ok=True)
    os.chmod(KEYS, 0o700)
    tmp = '%s.tmp%d' % (key_path(c), os.getpid())
    try:
        fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, 'w', encoding='utf-8') as f:
            f.write(k + '\n')
        os.rename(tmp, key_path(c))
    except OSError:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise


def echo_off():
    """Echo off, line mode (Enter ends a line). Returns the settings to put back, or None (not a terminal)."""
    import termios
    fd = sys.stdin.fileno()
    try:
        old = termios.tcgetattr(fd)
        new = termios.tcgetattr(fd)
        new[3] = (new[3] & ~(termios.ECHO | termios.ECHONL)) | termios.ICANON
        termios.tcsetattr(fd, termios.TCSADRAIN, new)
        return old
    except (termios.error, OSError):
        return None


PUSHBACK = []


def read_paste():
    """One message: a line, or - when a pasted key holds a line break - every line up to the paste's end mark, joined
    (with the line breaks kept, for pick_key). '' = end of input (Ctrl+D)."""
    raw = PUSHBACK.pop(0) if PUSHBACK else sys.stdin.readline()
    if not raw or '\x1b[200~' not in raw or '\x1b[201~' in raw or len(raw) >= 4095:
        return raw
    n = 0
    while n < 20 and len(raw) <= 600:
        more = sys.stdin.readline()
        if not more:
            break
        if '\x1b[200~' in more:
            PUSHBACK.append(more)
            break
        raw += more
        n += 1
        if '\x1b[201~' in more:
            break
    return raw


def pick_key(raw, ok, shape=None):
    """The key in a message: (key, why-not). One line: that line. Several lines: with the AI's exact key shape, the one
    line or the lines joined that has it (a key cut in two); else the one line that is a key when every other line
    could not be a piece of one (a label, a word); when no line is a key alone, the lines joined (a key cut up; the
    caller still checks it) unless its first lines already pass as a key (a word or a second key after them, or a key
    cut in three or more: asked again); else nothing ('lines': asked again) - never a guess between two keys, a piece
    of a key or a key with a word or another key stuck on saved."""
    lines = []
    for ln in re.split(r'[\r\n]+', PASTE.sub('', raw)):
        v = re.sub(r'[\x00-\x1f\x7f]', '', ln).strip()
        if v.lower().startswith('bearer '):
            v = v[7:].strip()
        if v:
            lines.append(v)
    if not lines:
        return '', ''
    if len(lines) == 1:
        return lines[0], ''
    joined = ''.join(lines)
    if shape:
        hits = [v for v in dict.fromkeys(lines + [joined]) if re.match(shape, v) and ok(v)]
        if len(hits) == 1:
            return hits[0], ''
        if len(hits) > 1:
            return '', 'lines'
    alone = [i for i, v in enumerate(lines) if ok(v)]
    if len(alone) == 1 and not any(KEY_PIECE.match(v) and v.lower() not in NOT_PIECES
                                   for i, v in enumerate(lines) if i != alone[0]):
        return lines[alone[0]], ''
    if not alone:
        if any(ok(''.join(lines[:i])) for i in range(1, len(lines))):
            return '', 'lines'
        return joined, ''
    return '', 'lines'


def ask_key(c, have=False):
    """Ask for the plan key (hidden) and save it. Returns the key, or '' when none came."""
    import termios, time
    k = c['key']
    say('')
    say(B + 'Sign in to %s with your %s' % (c['label'], c.get('account') or 'plan') + R)
    if k.get('url'):
        say('1. Open this link on your phone and copy your key:')
        say('   ' + k['url'])
        if k.get('where'):
            say(D + '   ' + k['where'] + R)
    say('2. Paste the key in the message box and send it. It stays hidden here and is kept only on this computer.')
    if have:
        say(D + 'A key is already saved on this computer - send a new one, or press Ctrl+D to keep using it.' + R)
    say('')
    flag = ''
    old = None
    sid = os.environ.get('TM_SESSION_ID', '')
    try:
        if re.match(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$', sid):
            try:
                os.makedirs(ASKING, mode=0o700, exist_ok=True)
                flag = os.path.join(ASKING, sid)
                with open(flag, 'w') as f:
                    f.write(str(os.getpid()))
            except OSError:
                flag = ''
        old = echo_off()
        while True:
            sys.stdout.write('Key (hidden): ')
            sys.stdout.flush()
            raw = read_paste()
            sys.stdout.write('\n')
            sys.stdout.flush()
            if raw == '':
                return ''
            v, why = pick_key(raw, lambda x: bool(KEY_OK.match(x) and (not k.get('re') or re.match(k['re'], x))),
                              k.get('shape'))
            if why == 'lines':
                say('That message has more than one line. Send only the key, on one line (Ctrl+C stops).')
                continue
            if not v:
                continue
            if '://' in v:
                say('That is a link, not the key. Open it on your phone, copy the key it shows and send that (Ctrl+C stops).')
                continue
            if KEY_OK.match(v) and (not k.get('re') or re.match(k['re'], v)):
                try:
                    save_key(c, v)
                    say(B + 'Key saved.' + R + D + ' Starting %s...' % c['label'] + R)
                except OSError as ex:
                    say('The key could not be saved on this computer (%s), so it is used for this start only.'
                        % (ex.strerror or 'error'))
                time.sleep(3)
                try:
                    termios.tcflush(sys.stdin.fileno(), termios.TCIFLUSH)
                except (termios.error, OSError):
                    pass
                return v
            say('That does not look like a %s key%s. Copy the whole key and send it again (Ctrl+C stops).'
                % (c['label'], (' (' + k['hint'] + ')') if k.get('hint') else ''))
    finally:
        if flag:
            try:
                os.unlink(flag)
            except Exception:
                pass
        if old is not None:
            try:
                termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, old)
            except Exception:
                pass


def put_key(c, e, key):
    names = (c.get('key') or {}).get('env') or []
    for n in ([names] if isinstance(names, str) else names):
        if key and re.match(r'^[A-Z][A-Z0-9_]{0,63}$', str(n)):
            e[n] = key
    if c.get('claudeDir'):
        claude_dir(c, e)


TRUST = []


def claude_dir(c, e):
    d = os.path.join(HOME, c['claudeDir'])
    os.makedirs(d, mode=0o700, exist_ok=True)
    e['CLAUDE_CONFIG_DIR'] = d
    e['CLAUDE_SECURESTORAGE_CONFIG_DIR'] = d
    if isinstance(c.get('claudeSeed'), dict):
        want = {k: v for k, v in c['claudeSeed'].items() if TRUST or k != 'projects'}
        if want:
            seed_file(os.path.join(d, '.claude.json'), want, 'force')


def _home_sub(v):
    if isinstance(v, dict):
        return {_home_sub(k): _home_sub(x) for k, x in v.items()}
    if isinstance(v, list):
        return [_home_sub(x) for x in v]
    return v.replace('$HOME', HOME) if isinstance(v, str) else v


def _merge(dst, src, force):
    for k, v in src.items():
        if isinstance(v, dict) and isinstance(dst.get(k), dict):
            _merge(dst[k], v, force)
        elif force or k not in dst:
            dst[k] = v


def seed_file(f, want, how):
    want = _home_sub(want)
    f = os.path.realpath(f)
    try:
        with open(f, encoding='utf-8') as fh:
            j = json.load(fh)
        if not isinstance(j, dict):
            return
    except FileNotFoundError:
        j = {}
    except (OSError, ValueError):
        return
    new = want if how == 'replace' else json.loads(json.dumps(j))
    if how != 'replace':
        _merge(new, want, how == 'force')
    if new == j and os.path.exists(f):
        return
    tmp = '%s.tm-tmp%d' % (f, os.getpid())
    try:
        os.makedirs(os.path.dirname(f), mode=0o700, exist_ok=True)
        fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, 'w', encoding='utf-8') as fh:
            json.dump(new, fh, indent=2)
            fh.write('\n')
        os.rename(tmp, f)
    except OSError:
        try:
            os.unlink(tmp)
        except OSError:
            pass


def seeds(c):
    for s in c.get('seed') or []:
        try:
            if isinstance(s, dict) and s.get('trust') and not TRUST:
                continue
            if isinstance(s, dict) and isinstance(s.get('json'), dict) and s.get('how') in ('fill', 'force', 'replace'):
                rel = os.path.normpath(str(s.get('path') or ''))
                if rel and not rel.startswith(('/', '..')):
                    seed_file(os.path.join(HOME, rel), s['json'], s['how'])
        except Exception:
            pass


MEM_STATE = os.environ.get('TM_MEMSHARE_STATE') or os.path.join(HOME, '.local', 'state', 'tm-memshare')
SID_RE = re.compile(r'^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$')


MEM_KEY = re.compile(r'^TM_MEM_[A-Z0-9_]+$')


def mem_launch(c, e):
    for k in [k for k in e if MEM_KEY.match(k)]:
        del e[k]
    try:
        _mem_launch(c, e)
    except Exception:
        for k in [k for k in e if MEM_KEY.match(k)]:
            del e[k]


def _mem_launch(c, e):
    sid = e.get('TM_SESSION_ID', '')
    if not SID_RE.match(sid):
        return
    d = os.path.join(MEM_STATE, 'launch', c['id'])
    dst = os.path.join(MEM_STATE, 'sessions', c['id'], sid)
    try:
        with open(os.path.join(d, 'launch.json'), encoding='utf-8') as f:
            spec = json.load(f)
    except (OSError, ValueError):
        spec = None
    ws = spec.get('workspace') if isinstance(spec, dict) else None
    if not isinstance(ws, dict) or not isinstance(ws.get('from'), str) or not os.path.isdir(ws['from']):
        if os.path.isdir(dst) and not os.path.islink(dst):
            shutil.rmtree(dst, ignore_errors=True)
        ws = None
    if not isinstance(spec, dict):
        return
    env = spec.get('env')
    for k, v in (env.items() if isinstance(env, dict) else ()):
        if MEM_KEY.match(str(k)) and isinstance(v, str) and os.path.exists(v):
            e[k] = v
    try:
        mem_allow(spec.get('allow'), e)
    except (OSError, ValueError):
        pass
    if not ws:
        return
    tmp = '%s.tmp%d' % (dst, os.getpid())
    try:
        shutil.rmtree(tmp, ignore_errors=True)
        shutil.copytree(ws['from'], tmp, symlinks=True)
        allow, ok = [], True
        try:
            with open(ws.get('userSettings') or '', encoding='utf-8') as f:
                mine = json.load(f)
            allow = ((mine.get('permissions') or {}).get('allow') or []) if isinstance(mine, dict) else None
            if not isinstance(allow, list) or not all(isinstance(x, str) for x in allow):
                ok = False
        except FileNotFoundError:
            allow = []
        except (OSError, ValueError, AttributeError):
            ok = False
        if ok:
            add = [x for x in ws.get('allow') or [] if isinstance(x, str) and x not in allow]
            with open(os.path.join(tmp, 'settings.json'), 'w', encoding='utf-8') as f:
                json.dump({'permissions': {'allow': allow + add}}, f, indent=2)
        if os.path.isdir(dst) and not os.path.islink(dst):
            shutil.rmtree(dst)
        os.rename(tmp, dst)
        os.utime(dst)
    except OSError:
        shutil.rmtree(tmp, ignore_errors=True)
        return
    if MEM_KEY.match(str(ws.get('env') or '')):
        e[ws['env']] = dst
    if ok and MEM_KEY.match(str(ws.get('settingsEnv') or '')):
        e[ws['settingsEnv']] = os.path.join(dst, 'settings.json')


def mem_allow(al, e):
    return


def _mem_allow_unused(al, e):
    if not isinstance(al, dict) or not isinstance(al.get('dirs'), list) or not isinstance(al.get('entries'), list):
        return
    if al.get('file') != 'permissions.json' or al.get('key') != 'mcpAllowlist':
        return
    x = (e.get('CURSOR_CONFIG_DIR') or '').strip()
    if not x:
        xdg = (e.get('XDG_CONFIG_HOME') or '').strip()
        x = os.path.join(xdg, 'cursor') if xdg else os.path.join(HOME, '.cursor')
    if x not in al['dirs'] or not os.path.isdir(x):
        return
    f = os.path.join(x, 'permissions.json')
    j = {}
    if os.path.exists(f):
        with open(f, encoding='utf-8') as fh:
            j = json.load(fh)
    if not isinstance(j, dict) or not isinstance(j.get('mcpAllowlist', []), list):
        return
    have = j.get('mcpAllowlist', [])
    add = [v for v in al['entries'] if isinstance(v, str) and v not in have]
    if not add:
        return
    j['mcpAllowlist'] = have + add
    text = json.dumps(j, indent=2) + '\n'
    if os.path.islink(f):
        with open(f, 'w', encoding='utf-8') as fh:
            fh.write(text)
        return
    tmp = '%s.tm-tmp%d' % (f, os.getpid())
    with open(tmp, 'w', encoding='utf-8') as fh:
        fh.write(text)
    os.rename(tmp, f)


AGY_LIST = os.path.join(HOME, '.local', 'state', 'tm-ai', 'agy-models.txt')
AGY_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max']
ANSI = re.compile(r'\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-Z\\-_]')


def gemini_pick(slug):
    w = re.match(r'^(gemini-[a-z0-9][a-z0-9.-]*?)-(low|medium|high|xhigh|max)$', slug)
    if not w:
        return slug
    try:
        if os.path.getsize(AGY_LIST) > 256 * 1024:
            return slug
        with open(AGY_LIST, encoding='utf-8', errors='replace') as f:
            text = ANSI.sub('', f.read())
    except OSError:
        return slug
    order, levels = [], {}
    for raw in re.split(r'\r?\n', text):
        if re.search(r'unavailable|not available|upgrade', raw, re.I):
            continue
        m = re.match(r'^\s*(gemini-[a-z0-9][a-z0-9.-]*?)-(low|medium|high|xhigh|max)(?:\s+(\S.*?))?\s*$', raw, re.I)
        if not m or len(m.group(1)) > 41:
            continue
        mid, lv = m.group(1).lower(), m.group(2).lower()
        if mid not in levels:
            if len(order) >= 12:
                continue
            order.append(mid)
            levels[mid] = set()
        levels[mid].add(lv)
    if not order:
        return slug
    mid = w.group(1) if w.group(1) in levels else order[0]
    ok = [x for x in AGY_LEVELS if x in levels[mid]]
    i = AGY_LEVELS.index(w.group(2))
    lv = next((AGY_LEVELS[j] for j in range(i, -1, -1) if AGY_LEVELS[j] in ok), ok[0])
    return mid + '-' + lv


SUB_MODELS = os.path.join(os.path.dirname(REG), 'sub-models.json')
PICK_MODEL_RE = r'^[A-Za-z0-9][A-Za-z0-9._/:+@-]{0,63}$'
PICK_LEVEL_RE = r'^[a-z][a-z0-9-]{0,15}$'
LADDER = ['none', 'off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']


def flag_value(argv, name, pat):
    if name not in argv[1:]:
        return ''
    i = argv.index(name, 1)
    v = argv[i + 1] if i + 1 < len(argv) else ''
    return v if re.match(pat, v) else ''


def sub_pick(c, model, effort):
    a = None
    try:
        if os.path.getsize(SUB_MODELS) <= 4 * 1024 * 1024:
            with open(SUB_MODELS, encoding='utf-8') as f:
                a = (json.load(f).get('ais') or {}).get(c['id'])
    except (OSError, ValueError, AttributeError):
        a = None
    if not isinstance(a, dict) or not isinstance(a.get('models'), list):
        return '', ''
    ms = {m['id']: m for m in a['models'] if isinstance(m, dict) and isinstance(m.get('id'), str)}
    if model and model not in ms:
        say(D + '%s is no longer on %s\'s model list - it starts on its own model.' % (model, c['label']) + R)
        model = ''
    m = ms.get(model or a.get('def') or '')
    lv = [x for x in (m.get('effort') or []) if isinstance(x, str)] if m else []
    if a.get('effortAtStart') is False or not lv:
        return model, ''
    if effort and effort not in lv:
        i = LADDER.index(effort) if effort in LADDER else -1
        down = [x for x in lv if x in LADDER and LADDER.index(x) < i]
        effort = max(down, key=LADDER.index) if down else ''
    if not effort and m.get('defEffort') in lv:
        effort = m['defEffort']
    return model, effort


def main(argv):
    if argv[:1] == ['--list']:
        for i, c in load().items():
            say('%s %d' % (i, 1 if find(c, env_for(c)) else 0))
        return 0
    if not argv or argv[0].startswith('-'):
        say('usage: tm-ai ID [--sign-in|--resume] [--model M] [--effort L] [--trust]   or   tm-ai --list')
        return 2
    regs = load()
    c = regs.get(argv[0])
    if not c:
        say('tm-ai: unknown AI "%s" (known: %s)' % (argv[0], ', '.join(sorted(regs))))
        return 2
    sign_in = '--sign-in' in argv[1:]
    resume = '--resume' in argv[1:]
    if '--trust' in argv[1:]:
        TRUST.append(True)
    if '--ask' in argv[1:]:
        i = argv.index('--ask', 1)
        q = argv[i + 1] if i + 1 < len(argv) else ''
        e = env_for(c)
        key = read_key(c) if c.get('key') else ''
        if not q or not c.get('ask') or not find(c, e) or (c.get('key') and not key):
            say('tm-ai: %s cannot be asked here' % c['label'])
            return 2
        shim()
        put_key(c, e, key)
        mem_launch(c, e)
        e['TM_AI_ASK'] = q
        signals_back()
        os.execvpe('bash', ['bash', '-c', 'exec ' + c['ask']], e)
    model = ''
    effort = flag_value(argv, '--effort', PICK_LEVEL_RE)
    v = flag_value(argv, '--model', PICK_MODEL_RE)
    if c['id'] == 'antigravity' and not effort and re.match(r'^gemini-[a-z0-9][a-z0-9.-]{1,60}-(low|medium|high|xhigh|max)$', v):
        model = gemini_pick(v)
    elif v or effort:
        model, effort = sub_pick(c, v, effort)
    shim()
    e = env_for(c)
    if not find(c, e):
        import fcntl
        os.makedirs(BASE, exist_ok=True)
        with open(os.path.join(BASE, c['id'] + '.lock'), 'w') as lk:
            try:
                fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except OSError:
                say(D + '%s is being set up in another session - waiting for it...' % c['label'] + R)
                fcntl.flock(lk, fcntl.LOCK_EX)
            e = env_for(c)
            if not find(c, e):
                if not install(c, e):
                    return 1
                e = env_for(c)
                say(B + '%s is installed.' % c['label'] + R)
    seeds(c)
    key = ''
    if c.get('key'):
        key = read_key(c)
        if sign_in or not key:
            got = ask_key(c, bool(key))
            if got:
                key = got
            elif key:
                say(D + 'No new key - using the one this computer already has.' + R)
        if not key:
            say('')
            say('No key yet, so %s cannot start. Type: tm-ai %s --sign-in   to try again.' % (c['label'], c['id']))
            return 1
    elif sign_in and c.get('login'):
        say('')
        say(B + 'Sign in to %s with your %s' % (c['label'], c.get('account') or 'account') + R)
        say(D + (c.get('loginSay') or 'Open the link below on your phone, approve it there, and this goes on by itself.') + R)
        if c.get('signInHint'):
            say(c['signInHint'])
        say('')
        rc, hit = run(c['login'], e, os.getcwd())
        say('')
        st = signed_in(c, e) if (hit or rc != 0 or c.get('loginCheck')) else None
        if st == 'out' or (hit and st != 'in'):
            say('Sign-in did not finish, so %s did not start. Type: tm-ai %s --sign-in   to try again.' % (c['label'], c['id']))
            return 1
    elif sign_in and c.get('signInHint'):
        say('')
        say(B + 'Sign in to %s with your %s' % (c['label'], c.get('account') or 'account') + R)
        say(c['signInHint'])
        say('')
    cmd = (c.get('resume') if resume else '') or c['launch']
    if key:
        say(D + 'If it says the key is not valid (API Error: 401), the key is wrong or has ended: type  tm-ai %s --sign-in'
            '  to send a new one.' % c['id'] + R)
    put_key(c, e, key)
    mem_launch(c, e)
    for k, val in (('TM_AI_MODEL', model), ('TM_AI_EFFORT', effort), ('TM_AI_TRUST', '1' if TRUST else '')):
        if val:
            e[k] = val
        else:
            e.pop(k, None)
    signals_back()
    os.execvpe('bash', ['bash', '-c', cmd if re.search(r'[;&|]', cmd) else 'exec ' + cmd], e)


if __name__ == '__main__':
    import signal
    try:
        import termios
        TTY.append(termios.tcgetattr(sys.stdin.fileno()))
    except Exception:
        pass
    for _s in (signal.SIGHUP, signal.SIGTERM):
        signal.signal(_s, stop)
    try:
        sys.exit(main(sys.argv[1:]))
    except KeyboardInterrupt:
        tty_back()
        say('')
        say('Stopped.')
        sys.exit(130)
