#!/usr/bin/env python3
"""Configure and launch the local Claude Code client with the Tars gateway."""
import getpass
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'
HOME_DIR = Path.home()
TOKEN_FILE = HOME_DIR / '.config/tars/claude-api-key'
SETTINGS_FILE = HOME_DIR / '.claude/settings.json'
RUNTIME_FILE = HOME_DIR / '.local/share/tars/claude-client.py'
LAUNCHER = HOME_DIR / '.local/bin/claude-tars'
# Match Tars Claude discovery. Allow the explicit priority model without
# resolving other gateway aliases into separately routed models.
MODEL_ID = re.compile(r'claude-(?:(?:opus|sonnet|haiku|fable|mythos)-[0-9]+(?:-[0-9]+)?(?:-[0-9]{8})?|mythos-preview)')
OPUS_PRIORITY_MODEL = 'claude-opus-5-5-fast'
PERSIAN_DIGITS = str.maketrans('0123456789.', '۰۱۲۳۴۵۶۷۸۹٫')
FAMILIES = ('haiku', 'sonnet', 'opus', 'fable')
CLIENT_ENV = {
    'ANTHROPIC_BASE_URL': BASE,
    'CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY': '1',
    'CLAUDE_CODE_MAX_RETRIES': '0',
    'API_TIMEOUT_MS': '600000',
    'CLAUDE_STREAM_FIRST_BYTE_TIMEOUT_MS': '600000',
    'CLAUDE_STREAM_IDLE_TIMEOUT_MS': '600000',
    'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC': '1',
}


class ClientError(Exception):
    pass


def read_settings():
    if not SETTINGS_FILE.exists():
        return {}
    value = json.loads(SETTINGS_FILE.read_text())
    if not isinstance(value, dict) or not isinstance(value.get('env', {}), dict):
        raise ClientError('Claude settings must contain a JSON object and an env object.')
    return value


def credential():
    key = os.environ.get('TARS_API_KEY', '').strip()
    if not key:
        try:
            info = TOKEN_FILE.lstat()
        except FileNotFoundError:
            raise ClientError('Add your personal Tars key: claude-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 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 + '/v1/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: claude-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):
    request = urllib.request.Request(BASE + '/v1/models', 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((8 << 20) + 1)
        if len(body) > 8 << 20:
            raise ClientError('The Tars model catalog is too large.')
        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('data'), list):
        raise ClientError('The Tars model catalog has an unexpected format.')
    models = {}
    for row in document['data']:
        if not isinstance(row, dict):
            continue
        model = row.get('id')
        if not isinstance(model, str) or (model != OPUS_PRIORITY_MODEL and not MODEL_ID.fullmatch(model)):
            continue
        label = row.get('display_name')
        label = label if isinstance(label, str) and label else model
        if model == OPUS_PRIORITY_MODEL:
            pricing = row.get('pricing')
            discount = pricing.get('discount_percent') if isinstance(pricing, dict) else None
            if not isinstance(discount, str) or not re.fullmatch(r'[0-9]{1,2}(?:\.[0-9]{1,2})?', discount):
                continue
            label += ' · ' + discount.translate(PERSIAN_DIGITS) + '٪ تخفیف'
        models[model] = label
    if not models:
        raise ClientError('This key has no permitted official-format Claude models. Check its scope and model access; gateway aliases are not renamed or substituted.')
    return models


def family_model(models, family):
    choices = [m for m in models if m != OPUS_PRIORITY_MODEL and m.removeprefix('anthropic/').startswith('claude-' + family + '-')]
    def order(model):
        return tuple(int(n) for n in re.findall(r'\d+', model)), not model.startswith('anthropic/'), model
    return max(choices, key=order) if choices else None


def session_settings(models, current):
    preferred = current.get('model')
    preferred = preferred.removeprefix('inferhub/') if isinstance(preferred, str) else ''
    if preferred in FAMILIES:
        preferred = family_model(models, preferred)
    selected = preferred if preferred in models else next((family_model(models, f) for f in FAMILIES if family_model(models, f)), sorted(models)[0])
    env = dict(CLIENT_ENV)
    for family in FAMILIES:
        env['ANTHROPIC_DEFAULT_' + family.upper() + '_MODEL'] = family_model(models, family) or selected
    return {
        'apiKeyHelper': 'python3 ' + shlex.quote(str(RUNTIME_FILE)) + ' --auth-helper',
        'model': selected,
        'availableModels': sorted(models),
        'modelPicker': {'replaceBuiltInOptions': True, 'options': [{'model': m, 'label': models[m], 'description': 'Tars / ' + m} for m in sorted(models)]},
        'env': env,
    }


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 install():
    settings = read_settings()
    # Backups stay private and outside the repository; never print their contents.
    originals = [p for p in (SETTINGS_FILE, HOME_DIR / '.zshrc', HOME_DIR / '.bashrc') if p.exists()]
    backup = HOME_DIR / '.local/state/tars/claude-client-backups'
    backup.mkdir(parents=True, exist_ok=True, mode=0o700)
    for path in originals:
        destination = backup / (path.name + '.before-tars')
        if not destination.exists():
            private_write(destination, path.read_text())
    settings['apiKeyHelper'] = 'python3 ' + shlex.quote(str(RUNTIME_FILE)) + ' --auth-helper'
    settings.setdefault('env', {})
    if settings['env'].get('ANTHROPIC_BASE_URL') == BASE and settings['env'].get('CLAUDE_CODE_MAX_OUTPUT_TOKENS') == '4096':
        del settings['env']['CLAUDE_CODE_MAX_OUTPUT_TOKENS']
    for name in list(settings['env']):
        if name.startswith('ANTHROPIC_DEFAULT_') or name in ('ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_MODEL', 'CLAUDE_CODE_SUBAGENT_MODEL', 'CLAUDE_CODE_RETRY_WATCHDOG'):
            del settings['env'][name]
    settings['env'].update(CLIENT_ENV)
    private_write(SETTINGS_FILE, json.dumps(settings, indent=2) + '\n')
    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)
    marker = '# BEGIN TARS_CLAUDE_CLIENT'
    block = '\n' + marker + '\nclaude() { "$HOME/.local/bin/claude-tars" "$@"; }\n# END TARS_CLAUDE_CLIENT\n'
    for path in (HOME_DIR / '.zshrc', HOME_DIR / '.bashrc'):
        text = path.read_text() if path.exists() else ''
        if marker not in text:
            private_write(path, text + block)
    print('Configured Claude Code for Tars. No credential was stored. Next: claude-tars --set-token')


def main(args):
    if args == ['--check-connection']:
        check_connection()
        return
    if args == ['--install']:
        install()
        return
    if args == ['--auth-helper']:
        sys.stdout.write(credential())
        return
    if args == ['--set-token']:
        if not sys.stdin.isatty():
            raise ClientError('Run claude-tars --set-token in your own interactive terminal.')
        key = getpass.getpass('Personal Tars API key (hidden): ').strip()
        models = catalog(key)
        TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
        private_write(TOKEN_FILE, key + '\n')
        print('Personal key saved privately. Permitted Claude models: ' + str(len(models)) + '. Run claude-tars, then /model.')
        return
    binary = shutil.which('claude')
    if not binary or Path(binary).resolve() == LAUNCHER.resolve():
        raise ClientError('Install the official Claude Code CLI before using this launcher.')
    if args and (args[0] in ('--version', '-v', '--help', '-h', 'doctor', 'update', 'install', 'auth')):
        os.execv(binary, [binary, *args])
    key = credential()
    models = catalog(key)
    if args == ['--models']:
        print('\n'.join(sorted(models)))
        return
    configuration = session_settings(models, read_settings())
    env = os.environ.copy()
    for name in list(env):
        if name.startswith('ANTHROPIC_DEFAULT_') or name in ('ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_MODEL', 'CLAUDE_CODE_SUBAGENT_MODEL', 'CLAUDE_CODE_RETRY_WATCHDOG', 'CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY', 'CLAUDE_CODE_USE_ANTHROPIC_AWS'):
            del env[name]
    env.update(configuration['env'])
    # No credential is included in argv or the generated settings object.
    os.execve(binary, [binary, '--settings', json.dumps(configuration), *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 Claude Code. Check your local file permissions and JSON settings.'
        print(message, file=sys.stderr)
        raise SystemExit(1)
