#!/usr/bin/env python3
"""Install and launch the official Codex CLI through the Tars public gateway."""
import getpass
import hashlib
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import socket
import ssl
import stat
import sys
import tempfile
import urllib.error
import urllib.request

BASE = 'https://api.tars.chat/v1'
CATALOG_URL = 'https://api.tars.chat/codex/v1/models'
HOME_DIR = Path.home()
TOKEN_FILE = HOME_DIR / '.config/tars/codex-api-key'
RUNTIME_FILE = HOME_DIR / '.local/share/tars/codex-client.py'
LAUNCHER = HOME_DIR / '.local/bin/codex-tars'
CACHE_DIR = HOME_DIR / '.cache/tars/codex-catalogs'
MODEL_ID = re.compile(r'(?:openai/)?(?:codex(?:-[a-z0-9.-]+)?|gpt-[0-9][a-z0-9.-]*-codex(?:-[a-z0-9.-]+)?|gpt-5\.[45](?:-(?:mini|nano|pro))?|gpt-(?:5\.6|6(?:\.[0-9]+)?)-(?:astra|luna|sol|terra)(?:-pro)?)')


class ClientError(Exception):
    pass


def private_write(path, text, executable=False):
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, temporary = tempfile.mkstemp(prefix='.' + path.name + '-', dir=path.parent)
    try:
        os.fchmod(fd, 0o700 if executable else 0o600)
        with os.fdopen(fd, 'w') as target:
            target.write(text)
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


def credential():
    key = os.environ.get('TARS_CODEX_API_KEY', '').strip()
    if not key:
        try:
            info = TOKEN_FILE.lstat()
        except FileNotFoundError:
            raise ClientError('Enter your personal Tars key: codex-tars --set-token') from None
        if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
            raise ClientError('The personal Codex key file must be owned by you and have mode 600.')
        key = TOKEN_FILE.read_text().strip()
    if not key or len(key) > 4096 or any(c.isspace() for c in key):
        raise ClientError('The personal Tars key is missing or invalid.')
    return key


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, request, fp, code, msg, headers, newurl):
        return None


def network_error(error):
    # Reasons can contain proxy credentials or response text: never echo them.
    reason = error.reason if isinstance(error, urllib.error.URLError) else error
    if isinstance(reason, ssl.SSLCertVerificationError):
        return ClientError('[TLS_CERTIFICATE] Python could not verify api.tars.chat. Check the system clock and Python CA certificates; use SSL_CERT_FILE for an administrator-approved CA bundle. Do not disable TLS verification.')
    if isinstance(reason, ssl.SSLError):
        return ClientError('[TLS_HANDSHAKE] The HTTPS handshake with api.tars.chat failed. Check your network and TLS inspection settings.')
    if isinstance(reason, socket.gaierror):
        return ClientError('[DNS] Your laptop could not resolve api.tars.chat. Check DNS and your network connection.')
    if isinstance(reason, TimeoutError):
        return ClientError('[TIMEOUT] Connecting to api.tars.chat timed out. Check network access and any configured HTTPS proxy.')
    if isinstance(reason, ConnectionRefusedError):
        return ClientError('[CONNECTION_REFUSED] The connection was refused. Check your network and any configured HTTPS proxy.')
    return ClientError('[CONNECTION_FAILED] Could not connect to api.tars.chat. Check network access and HTTPS proxy configuration.')


def http_error(code):
    if code == 401:
        detail = 'The personal key was rejected. Check whether it is correct, active and unrevoked.'
    elif code == 403:
        detail = 'Access was denied. Check key permissions, subscription and network/CDN access rules.'
    elif code == 407:
        detail = 'The configured proxy requires authentication.'
    elif code == 429:
        detail = 'The catalog request was rate limited. Wait before trying again.'
    elif 300 <= code < 400:
        detail = 'A redirect was refused to protect your key. Check gateway or network configuration.'
    elif code >= 500:
        detail = 'The gateway or network proxy is temporarily unavailable. Try again later.'
    else:
        detail = 'The gateway or network proxy returned an unexpected response.'
    return ClientError('[HTTP_' + str(code) + '] ' + detail)


def check_connection():
    # Same HTTPS/proxy policy as authenticated discovery; no credential is read.
    request = urllib.request.Request(BASE + '/models', headers={'Accept': 'application/json'})
    try:
        opener = urllib.request.build_opener(urllib.request.ProxyHandler(), NoRedirect())
        with opener.open(request, timeout=20):
            pass
    except urllib.error.HTTPError as error:
        code = error.code
        error.close()
        if code == 401:
            print('Verified HTTPS connection to api.tars.chat succeeded (HTTP 401; no key sent). Next: codex-tars --set-token')
            return
        raise http_error(code) from None
    except (OSError, ValueError) as error:
        raise network_error(error) from None
    raise ClientError('[UNEXPECTED_AUTH_RESPONSE] The public catalog did not require authentication. Check the gateway or network before entering a key.')

def catalog(key, require_models=True):
    request = urllib.request.Request(CATALOG_URL, headers={'Authorization': 'Bearer ' + key})
    try:
        opener = urllib.request.build_opener(urllib.request.ProxyHandler(), NoRedirect())
        with opener.open(request, timeout=20) as response:
            body = response.read((1 << 20) + 1)
        if len(body) > 1 << 20:
            raise ClientError('The catalog exceeds the Codex 1 MiB limit.')
        document = json.loads(body)
    except urllib.error.HTTPError as error:
        code = error.code
        error.close()
        raise http_error(code) from None
    except (OSError, ValueError) as error:
        if isinstance(error, (json.JSONDecodeError, UnicodeError)):
            raise ClientError('[CATALOG_FORMAT] Expected a JSON catalog from api.tars.chat. A gateway, proxy or captive portal may have returned a different response.') from None
        raise network_error(error) from None
    if not isinstance(document, dict) or not isinstance(document.get('models'), list):
        raise ClientError('Tars did not return a Codex-native model catalog.')
    models = []
    seen = set()
    for row in document['models']:
        if not isinstance(row, dict):
            raise ClientError('The Codex catalog contains an invalid entry.')
        name = row.get('slug')
        if not isinstance(name, str) or not MODEL_ID.fullmatch(name):
            raise ClientError('The gateway returned an unexpected non-Codex model; launch stopped.')
        if name in seen:
            raise ClientError('The gateway returned duplicate Codex model identities.')
        seen.add(name)
        models.append(row)
    if require_models and not models:
        raise ClientError('This key has no permitted Codex-compatible models. Check its model scope and active plan. Current GPT families such as gpt-6-luna are supported when returned by the authorized catalog.')
    # Preserve the native instructions and capability fields supplied by Tars.
    return {'models': models}


def requested_model(args):
    selected = None
    for index, arg in enumerate(args):
        if arg == '--':
            break
        if arg in ('--model', '-m'):
            if index + 1 >= len(args):
                raise ClientError('Provide a model ID after --model.')
            selected = args[index + 1]
        elif arg.startswith('--model='):
            selected = arg.split('=', 1)[1]
    return selected


def native_defaults():
    # Reading only: preserve a permitted native user choice without rewriting
    # config, state, auth, profiles, permissions or CODEX_HOME.
    folder = Path(os.environ.get('CODEX_HOME', str(HOME_DIR / '.codex')))
    path = folder / 'config.toml'
    if path.is_file():
        text = path.read_text()
        try:
            import tomllib
            return tomllib.loads(text)
        except ImportError:
            root = re.split(r'(?m)^\s*\[', text, maxsplit=1)[0]
            values = {}
            for name in ('model', 'model_reasoning_effort'):
                found = re.search(r'''(?m)^\s*''' + name + r'''\s*=\s*["']([A-Za-z0-9._/-]+)["']''', root)
                if found:
                    values[name] = found.group(1)
            return values
    return {}


def choose_model(document, args):
    names = [row['slug'] for row in document['models']]
    explicit = requested_model(args) or os.environ.get('TARS_CODEX_MODEL')
    if explicit:
        if explicit not in names:
            raise ClientError('The selected model is not in this key\'s Codex catalog. Run codex-tars --models.')
        return explicit
    preferred = native_defaults().get('model')
    if preferred in names:
        return preferred
    return names[0]


def toml_value(value):
    if isinstance(value, dict):
        return '{' + ','.join(key + '=' + toml_value(item) for key, item in value.items()) + '}'
    return json.dumps(value, ensure_ascii=False)


def session_overrides(document, model, args=()):
    entry = next(row for row in document['models'] if row['slug'] == model)
    levels = [row.get('effort') for row in entry.get('supported_reasoning_levels', [])
              if isinstance(row, dict) and row.get('effort') in ('none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max')]
    effort = None
    if levels:
        explicit = None
        for index, arg in enumerate(args):
            if arg == '--':
                break
            setting = ''
            if arg in ('-c', '--config') and index + 1 < len(args):
                setting = args[index + 1]
            elif arg.startswith('--config='):
                setting = arg.removeprefix('--config=')
            if setting.startswith('model_reasoning_effort='):
                explicit = setting.split('=', 1)[1].strip().strip('\"\'')
        if explicit is not None and explicit not in levels:
            raise ClientError('This reasoning level is not supported for the model. Choose: ' + ', '.join(levels))
        saved = None if '--ignore-user-config' in args else native_defaults().get('model_reasoning_effort')
        preferred = entry.get('default_reasoning_level')
        if explicit is not None:
            effort = explicit
        elif saved in levels:
            effort = saved
        else:
            effort = preferred if preferred in levels else levels[0]
    CACHE_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
    data = json.dumps(document, ensure_ascii=False, sort_keys=True) + '\n'
    # Content-addressed metadata prevents two different keys' sessions from
    # overwriting each other's catalog. This file never contains a credential.
    path = CACHE_DIR / (hashlib.sha256(data.encode()).hexdigest() + '.json')
    private_write(path, data)
    provider = {
        'name': 'Tars', 'base_url': BASE, 'model_catalog_url': CATALOG_URL,
        'env_key': 'TARS_CODEX_API_KEY', 'wire_api': 'responses',
        'requires_openai_auth': False, 'supports_websockets': False,
        'request_max_retries': 0, 'stream_max_retries': 0,
        'stream_idle_timeout_ms': 600000,
        'capabilities': {'remote_compaction': 'unsupported'},
    }
    settings = {'model_provider': 'tars', 'model': model, 'model_catalog_json': str(path),
                'features.api_key_model_discovery': True,
                'model_providers.tars': provider}
    if effort is not None:
        settings['model_reasoning_effort'] = effort
    args = []
    for name, value in settings.items():
        args.extend(['-c', name + '=' + toml_value(value)])
    return args


def install():
    private_write(RUNTIME_FILE, Path(__file__).read_text(), executable=True)
    private_write(LAUNCHER, '#!/bin/sh\nexec python3 ' + shlex.quote(str(RUNTIME_FILE)) + ' "$@"\n', executable=True)
    backup = HOME_DIR / '.local/state/tars/codex-client-backups'
    backup.mkdir(parents=True, exist_ok=True, mode=0o700)
    marker = '# BEGIN TARS_CODEX_CLIENT'
    block = '\n' + marker + '\ncodex() { "$HOME/.local/bin/codex-tars" "$@"; }\n# END TARS_CODEX_CLIENT\n'
    for profile in (HOME_DIR / '.zshrc', HOME_DIR / '.bashrc'):
        text = profile.read_text() if profile.exists() else ''
        if marker in text:
            continue
        if profile.exists() and not (backup / (profile.name + '.before-tars')).exists():
            private_write(backup / (profile.name + '.before-tars'), text)
        private_write(profile, text + block)
    print('Codex Tars launcher installed. Native Codex config and credentials are unchanged. Next: codex-tars --set-token')


def main(args):
    if args == ['--check-connection']:
        check_connection()
        return
    if args == ['--install']:
        install()
        return
    if args == ['--set-token']:
        if not sys.stdin.isatty():
            raise ClientError('Run codex-tars --set-token in your own interactive terminal.')
        key = getpass.getpass('Personal Tars Codex API key (hidden): ').strip()
        document = catalog(key, require_models=False)
        TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
        private_write(TOKEN_FILE, key + '\n')
        if document['models']:
            print('Personal key saved privately. Permitted Codex models: ' + str(len(document['models'])) + '. Run codex-tars, then /model.')
        else:
            print('Key saved privately, but no Codex model is assigned. Launch stays blocked until the key and plan have Codex access.')
        return
    binary = shutil.which('codex')
    if not binary or Path(binary).resolve() == LAUNCHER.resolve():
        raise ClientError('Install the official Codex CLI before using this launcher.')
    if args and args[0] in ('--version', '-V', '--help', '-h', 'help', 'login', 'logout', 'completion', 'features'):
        os.execv(binary, [binary, *args])
    key = credential()
    document = catalog(key)
    if args == ['--models']:
        print('\n'.join(row['slug'] for row in document['models']))
        return
    model = choose_model(document, args)
    overrides = session_overrides(document, model, args)
    env = os.environ.copy()
    env['TARS_CODEX_API_KEY'] = key
    # Credential is scoped to the child environment; never argv/config/catalog.
    os.execve(binary, [binary, *overrides, *args], env)


if __name__ == '__main__':
    try:
        main(sys.argv[1:])
    except (ClientError, OSError, ValueError) as error:
        message = str(error) if isinstance(error, ClientError) else 'Could not configure Codex. Check local permissions and TOML settings.'
        print(message, file=sys.stderr)
        raise SystemExit(1)
