#!/usr/bin/env python3
"""LushLux local Codex setup. Contains a client key; do not share."""
import datetime
import json
import os
import re
import tempfile
from pathlib import Path
try:
    import tomllib
except ImportError:
    raise SystemExit('Use Python 3.11 or newer for safe TOML validation.')

def browser_authorize():
    import time
    import urllib.error
    import urllib.parse
    import urllib.request
    import webbrowser
    site = '' or input('LushLux website HTTPS address: ').strip()
    site = site.rstrip('/')
    parsed = urllib.parse.urlsplit(site)
    if parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('', '/'):
        raise ValueError('Website must be an HTTPS origin without a path')
    class NoRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, req, fp, code, msg, headers, newurl):
            return None
    opener = urllib.request.build_opener(NoRedirect)
    def post(route, obj):
        request = urllib.request.Request(site + route, data=json.dumps(obj).encode(), headers={'Content-Type':'application/json'}, method='POST')
        try:
            with opener.open(request, timeout=20) as response:
                return response.status, json.loads(response.read(1000000))
        except urllib.error.HTTPError as exc:
            if exc.code == 429:
                return 429, {}
            raise ValueError('LushLux authorization failed (HTTP ' + str(exc.code) + ')') from None
        except (urllib.error.URLError, TimeoutError):
            raise ValueError('Cannot reach LushLux HTTPS website; check the address and connection') from None
    code, grant = post('/api/device/start', {})
    verification = str(grant['verification_uri'])
    if not verification.startswith('/?device='):
        raise ValueError('Unexpected verification URI')
    target = site + verification
    print('Open:', target)
    print('Confirmation code:', grant['user_code'])
    print('Sign into your LushLux account and approve only this code.')
    webbrowser.open(target)
    expiry = time.monotonic() + min(int(grant.get('expires_in',600)), 600)
    interval = max(5, int(grant.get('interval',5)))
    while time.monotonic() < expiry:
        time.sleep(interval)
        status, data = post('/api/device/poll', {'device_code': grant['device_code']})
        if status == 202:
            continue
        if status == 429:
            interval = min(interval + 5, 30)
            continue
        if status != 200 or not data.get('api_key'):
            raise ValueError('Authorization was not completed')
        key = str(data['api_key'])
        url = str(data['public_api_url']).rstrip('/')
        u = urllib.parse.urlsplit(url)
        if u.scheme not in ('http','https') or not u.hostname or u.username or u.password or u.query or u.fragment:
            raise ValueError('Invalid API address returned by server')
        if not u.path.endswith('/v1'):
            url += '/v1'
        models = [m for m in data.get('models',[]) if m.get('type','text') in ('text','chat') and m.get('enabled',True)]
        if not models:
            raise ValueError('No available text models on this key')
        model = str(models[0]['id'])
        q = lambda s: json.dumps(str(s), ensure_ascii=False)
        basic = ('[model_providers.lushlux]\nname = "LushLux"\nbase_url = ' + q(url) + '\nwire_api = "responses"\nexperimental_bearer_token = ' + q(key) + '\nrequires_openai_auth = false\nsupports_websockets = false\nrequest_max_retries = 0\nstream_max_retries = 0\nstream_idle_timeout_ms = 360000\n\n[profiles.lushlux]\nmodel_provider = "lushlux"\nmodel = ' + q(model) + '\n')
        basic += 'developer_instructions = ' + q('For image generation or image editing through LushLux, use the configured LushLux media MCP tools. First list tools and enabled models, then select the exact enabled image model and call generation once. Use the upload/edit tools for references and video tools for video tasks when advertised by the gateway. The customer key is configured in MCP headers; a separate upstream OPENAI_API_KEY is not needed. Display actual returned image content or image URLs. Claim success only after the tool succeeds. If media tools are missing, report the connection problem. Do not invent images or replace requested media with operating system settings changes, wallpapers, scripts, or unrelated substitutes. Do not automatically repeat paid generation after an uncertain timeout. Explain the exact gateway error. Catalog membership does not prove upstream model access. Local file/terminal operations are performed by the Codex client using the tools and permissions granted in this session. When asked to install a local skill, inspect available tools and the local skill instructions; do not claim terminal access is unavailable without checking the client tools. This instruction grants no additional permissions.') + '\n'
        media = ('\n[mcp_servers.lushlux_media]\nurl = ' + q(url.removesuffix('/v1') + '/mcp') + '\nhttp_headers = { Authorization = ' + q('Bearer ' + key) + ' }\nenabled = true\nstartup_timeout_sec = 30\ntool_timeout_sec = 600\n')
        print('LushLux authorization approved. Client key received securely over HTTPS.')
        return {'model':model,'basic':basic,'with_media':basic+media}
    raise ValueError('Authorization expired. Run setup again.')

PAYLOAD = browser_authorize()
BEGIN = '# BEGIN LUSHLUX MANAGED PROFILE'
END = '# END LUSHLUX MANAGED PROFILE'

def main():
    directory = Path(os.environ.get('CODEX_HOME') or Path.home() / '.codex').expanduser()
    path = directory / 'config.toml'
    if path.is_symlink() or directory.is_symlink():
        raise ValueError('Refusing symbolic link configuration')
    text = path.read_text(encoding='utf-8') if path.exists() else ''
    if BEGIN in text:
        if text.count(BEGIN) != 1 or text.count(END) != 1:
            raise ValueError('Managed markers are inconsistent. No changes made.')
        text = re.sub(re.escape(BEGIN) + r'.*?' + re.escape(END) + r'\n?', '', text, flags=re.S)
    parsed = tomllib.loads(text)
    if 'lushlux' in parsed.get('model_providers', {}) or 'lushlux' in parsed.get('profiles', {}):
        raise ValueError('Existing unmanaged LushLux profile detected. Merge manually.')
    use_media = input('Enable LushLux media MCP (/mcp)? [Y/n]: ').strip().lower() != 'n'
    block = PAYLOAD['with_media'] if use_media else PAYLOAD['basic']
    # Root values are edited only before the first TOML table; user approvals and sandbox stay intact.
    use_default = input('Use LushLux by default in Codex app/CLI? [y/N]: ').strip().lower() == 'y'
    if use_default:
        match = re.search(r'^\s*\[', text, flags=re.M)
        split = match.start() if match else len(text)
        root, rest = text[:split], text[split:]
        root = re.sub(r'^\s*(model|model_provider)\s*=.*(?:\n|$)', '', root, flags=re.M)
        root = 'model_provider = "lushlux"\nmodel = ' + json.dumps(PAYLOAD['model']) + '\n' + root
        text = root + rest
    result = text.rstrip() + '\n\n' + BEGIN + '\n' + block + END + '\n'
    tomllib.loads(result)
    print('Target:', path)
    print('Existing skills, plugins, sandbox and approval policy are preserved.')
    print('Browser ChatGPT login is separate; this profile uses your LushLux key.')
    if input('Save configuration and private backup? [y/N]: ').strip().lower() != 'y':
        return
    directory.mkdir(parents=True, exist_ok=True)
    if path.exists():
        stamp = datetime.datetime.now().strftime('%Y%m%d-%H%M%S-%f')
        backup = path.with_name('config.toml.backup-' + stamp)
        fd = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, 'wb') as f:
            f.write(path.read_bytes())
        print('Backup:', backup)
    fd, temp = tempfile.mkstemp(prefix='.lushlux-', dir=directory)
    try:
        with os.fdopen(fd, 'w', encoding='utf-8') as f:
            f.write(result)
        os.chmod(temp, 0o600)
        os.replace(temp, path)
    finally:
        if os.path.exists(temp):
            os.unlink(temp)
    print('Restart Codex. CLI: codex --profile lushlux')
    print('Open your project folder. File and terminal tools are supplied by the local client.')
    print('If a tool is missing, check client permissions and gateway Responses tool support.')

if __name__ == '__main__':
    try:
        main()
    except Exception as exc:
        print('Setup stopped:', str(exc))
        raise SystemExit(1)
