#!/usr/bin/env python3
# Copyright 2026 Stephen William Wiley
# This software comes with absolutely no warranty or implied warranty.
# You may modify and redistribute it provided this notice remains intact.
# By using this software you agree to the terms of this license.

"""Default-loaded, removable proxy GUI commands plus the Codex proxy backend."""

from __future__ import annotations

import os as _os
import sys as _sys

# This combined module also provides the codex_proxy module name expected by ProxyUI.

_windows = {}


def _dispatch(tk_root, operation, arg):
    bridge = getattr(tk_root, '_agent_ui', None)
    if bridge is None:
        print('Proxy commands require the GUI.')
        return
    bridge.call(bridge.module(__name__), operation, {'arg': arg})


def cmd_run_proxy(agent, arg, *, input=None, tk_root=None):
    """Open the Codex proxy window and configure the ready proxy."""
    return _dispatch(tk_root, '_frontend_proxy', arg)


def cmd_codex_login(agent, arg, *, input=None, tk_root=None):
    """Open the Codex login window."""
    return _dispatch(tk_root, '_frontend_login', arg)


def _frontend_proxy(*, tk_root, bridge, arg=''):
    return _proxy_ui(tk_root, bridge).start(False)


def _frontend_login(*, tk_root, bridge, arg=''):
    return _proxy_ui(tk_root, bridge).start(True)


def _proxy_ui(root, bridge):
    if root not in _windows:
        _windows[root] = ProxyUI(root, bridge)
    return _windows[root]


def _close_ui(root):
    ui = _windows.pop(root, None)
    if ui is not None:
        ui.close()


class ProxyUI:
    """Tk owns widgets; readers and health checks publish local events only."""

    def __init__(self, root, bridge):
        import queue
        import threading
        self.root, self.bridge = root, bridge
        self.descriptor = bridge.module(__name__)
        self.directory = bridge.workspace['directory']
        self.sessions = {}
        self.events = queue.Queue()
        self.closing = threading.Event()
        self.pending = None
        self.timer = root.after(50, self.poll)

    def output(self, session, text):
        widget = session['output']
        view = widget.yview()
        widget.configure(state='normal')
        widget.insert('end', text)
        widget.configure(state='disabled')
        if not view or view[1] == 1.0:
            widget.see('end')

    def start(self, login=False):
        if self.closing.is_set():
            return
        import subprocess
        import threading
        import tkinter as tk
        session = self.sessions.get(login)
        if session is not None:
            session['window'].deiconify()
            session['window'].lift()
            if session['process'] is not None and session['process'].poll() is None:
                return
        else:
            window = tk.Toplevel(self.root)
            window.title('Codex login' if login else 'Codex proxy')
            window.geometry('800x400')
            window.protocol('WM_DELETE_WINDOW', window.withdraw)
            output = tk.Text(window, wrap='word', state='disabled')
            scrollbar = tk.Scrollbar(window, command=output.yview)
            output.configure(yscrollcommand=scrollbar.set)
            scrollbar.pack(side='right', fill='y')
            output.pack(fill='both', expand=True)
            session = {'window': window, 'output': output, 'process': None}
            self.sessions[login] = session
        command = [_sys.executable]
        if not getattr(_sys, 'frozen', False):
            # Resolve the host, not this module's saved/imported source path.
            import agent
            command.extend(['-u', _os.path.abspath(__file__)])
        command.append('--just-proxy')
        if login:
            command.append('--login')
        env = _os.environ.copy()
        env.update(PYTHONUNBUFFERED='1', PYTHONIOENCODING='utf-8')
        try:
            process = subprocess.Popen(command, stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, env=env,
                creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0)
                if _sys.platform == 'win32' else 0)
        except OSError as error:
            self.output(session, 'Cannot start process: ' + str(error) + '\n')
            return
        if self.pending is not None and self.pending[0] is session:
            self.pending = None
        session['process'] = process
        self.output(session, 'Starting login…\n' if login else 'Starting proxy…\n')
        threading.Thread(target=self.read_output, args=(session, process),
                         name='proxy-output', daemon=True).start()
        if not login:
            api = 'http://%s:%s/v1' % (HOST, PORT)
            threading.Thread(target=self.check_health, args=(session, process, api),
                             name='proxy-health', daemon=True).start()

    def read_output(self, session, process):
        import codecs
        decoder = codecs.getincrementaldecoder('utf-8')('replace')
        def emit(text):
            self.events.put(('output', (session, process, text)))
        try:
            while True:
                data = process.stdout.read1(4096)
                if not data:
                    break
                emit(decoder.decode(data))
            emit(decoder.decode(b'', final=True))
        except (OSError, ValueError) as error:
            emit(str(error) + '\n')
        finally:
            process.stdout.close()
            code = process.wait()
            emit('Process exited: %s\n' % code)

    def check_health(self, session, process, api):
        import json
        import time
        import urllib.request
        opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
        deadline = time.monotonic() + 120
        while not self.closing.is_set() and process.poll() is None and time.monotonic() < deadline:
            try:
                with opener.open(api + '/health', timeout=1) as response:
                    health = json.load(response)
                if (isinstance(health, dict) and health.get('ok') is True
                        and health.get('pid') == process.pid and process.poll() is None):
                    self.events.put(('ready', (session, process, api)))
                    return
            except (OSError, ValueError):
                pass
            if self.closing.wait(0.2):
                return
        if not self.closing.is_set() and process.poll() is None:
            self.events.put(('output', (session, process,
                'Readiness timed out; configuration unchanged.\n')))
            try:
                process.terminate()
            except OSError:
                pass
            self.reap(process)

    @staticmethod
    def reap(child):
        import subprocess
        try:
            child.wait(timeout=2)
        except subprocess.TimeoutExpired:
            try:
                child.kill()
            except OSError:
                pass
            child.wait()

    def poll(self):
        import json
        import queue
        if self.closing.is_set():
            return
        while True:
            try:
                kind, (session, process, value) = self.events.get_nowait()
            except queue.Empty:
                break
            if session['process'] is not process:
                continue
            if kind == 'output':
                self.output(session, value)
            elif process.poll() is None:
                self.pending = (session, process, value)
        if self.pending is not None and self.bridge.available():
            session, process, api = self.pending
            if session['process'] is not process or process.poll() is not None:
                self.pending = None
            elif self.bridge.workspace['directory'] != self.directory:
                self.pending = None
            else:
                # Snapshot only at the idle boundary. /config persists and applies
                # through the existing worker-owned configuration command.
                values = dict(self.bridge.workspace['config'])
                values.update(api=api, api_key='dummy')
                if self.bridge.submit_command('/config ' + json.dumps(values)):
                    self.pending = None
        self.timer = self.root.after(50, self.poll)

    def close(self):
        import threading
        self.closing.set()
        self.pending = None
        self.root.after_cancel(self.timer)
        for session in self.sessions.values():
            process = session['process']
            if process is not None and process.poll() is None:
                try:
                    process.terminate()
                except OSError:
                    pass
                threading.Thread(target=self.reap, args=(process,),
                                 name='proxy-shutdown', daemon=True).start()
            session['window'].destroy()
        self.sessions.clear()


cmd_run_proxy.ui = {'menu': 'File', 'label': 'run_proxy', 'direct': True,
    'frontend': '_frontend_proxy', 'cleanup': '_close_ui', 'safe_during_inference': True}
cmd_codex_login.ui = {'menu': 'File', 'label': 'codex_login', 'direct': True,
    'frontend': '_frontend_login', 'cleanup': '_close_ui', 'safe_during_inference': True}

import argparse, base64, hashlib, http.server, json, os, secrets, sys, threading, time, uuid
import shlex, urllib.error, urllib.parse, urllib.request, webbrowser
from typing import Any

HOST = "127.0.0.1"
PORT = 8787
AUTH_PATH = os.path.join(os.path.expanduser("~"), ".agentfiles","codex_auth.json")
CODEX_URL = "https://chatgpt.com/backend-api/codex/responses"
CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"
USER_AGENT= "Melder/30"
AUTH_URL = "https://auth.openai.com/oauth/authorize"
TOKEN_URL = "https://auth.openai.com/oauth/token"
REDIRECT = "http://localhost:1455/auth/callback"
SCOPE = "openid profile email offline_access"
# Identify this client honestly rather than impersonating Codex CLI/OpenCode.
ORIGINATOR = "melder"
CODEX_MODELS_URL = "https://chatgpt.com/backend-api/codex/models"
# agent.py reads n_ctx from /props and context_length from /models
CONTEXT_LENGTH = 1_000_000
# Cached live model ids from Codex (filled by fetch_available_models)
_models_cache: list = []
_models_cache_at: float = 0.0
_MODELS_CACHE_TTL = 300.0
# Protect all local auth database reads, writes, and refresh-token rotation.
# Inference streams are independent and are not serialized.
_auth_lock = threading.RLock()


class ProxyError(Exception):
    def __init__(self, status: int, payload, *, login: bool = False):
        error = payload
        if isinstance(payload, dict) and isinstance(payload.get("error"), dict):
            error = payload["error"]
        self.error = dict(error) if isinstance(error, dict) else {"message": str(error)}
        self.error.setdefault("type", "upstream_error")
        self.error.setdefault("message", self.error.get("error_description") or
                              self.error.get("error") or "Upstream request failed")
        if login:
            self.error["message"] = (str(self.error["message"]) +
                ". Re-login required. Run: python3 codex_proxy.py --login --auth-file " +
                shlex.quote(AUTH_PATH))
        self.status = status
        super().__init__(str(self.error["message"]))


def _requires_login(payload) -> bool:
    text = json.dumps(payload).lower()
    return any(s in text for s in ("revoked", "invalid_grant", "token_invalidated",
                                   "refresh_token_reused", "refresh_token_expired"))


def _http_error(e: urllib.error.HTTPError, *, login: bool = False) -> ProxyError:
    try:
        raw = e.read().decode("utf8", "replace")
    except Exception as read_error:
        raw = f"{e}; could not read upstream error body: {read_error}"
    finally:
        e.close()
    try:
        payload = json.loads(raw)
    except json.JSONDecodeError:
        payload = {"message": raw or str(e)}
    return ProxyError(e.code, payload, login=login or _requires_login(payload))


# ---------------------------------------------------------------------------
# Auth
# ---------------------------------------------------------------------------

def _jwt_claims(token: str) -> dict:
    try:
        part = (token or "").split(".")[1]
        part += "=" * (-len(part) % 4)
        return json.loads(base64.urlsafe_b64decode(part.encode("ascii")))
    except Exception:
        return {}


def account_id_from(access: str, id_token: str = "") -> str:
    # Match OpenCode: prefer id_token, then access_token; accept the organization
    # fallback used by older token shapes.
    for tok in (id_token, access):
        c = _jwt_claims(tok)
        if c.get("chatgpt_account_id"):
            return str(c["chatgpt_account_id"])
        auth = c.get("https://api.openai.com/auth")
        if isinstance(auth, dict) and auth.get("chatgpt_account_id"):
            return str(auth["chatgpt_account_id"])
        orgs = c.get("organizations")
        if isinstance(orgs, list) and orgs and isinstance(orgs[0], dict) and orgs[0].get("id"):
            return str(orgs[0]["id"])
    return ""


def residency_from(access: str) -> str:
    c = _jwt_claims(access)
    auth = c.get("https://api.openai.com/auth")
    value = auth.get("chatgpt_compute_residency") if isinstance(auth, dict) else None
    value = value or c.get("chatgpt_compute_residency")
    return "" if not value or value == "no_constraint" else str(value)


def load_auth(path: str | None = None) -> dict | None:
    with _auth_lock:
        return _load_auth_unlocked(path)

def _load_auth_unlocked(path: str | None = None) -> dict | None:
    for p in ([path] if path else [AUTH_PATH]):
        if not p or not os.path.isfile(p):
            continue
        try:
            data = json.load(open(p, encoding="utf8"))
        except (OSError, json.JSONDecodeError):
            continue
        tokens = data.get("tokens") if isinstance(data.get("tokens"), dict) else data
        access = (tokens.get("access_token") or data.get("access_token")
                  or data.get("access") or "").strip()
        if not access:
            continue
        idt = (tokens.get("id_token") or data.get("id_token") or "").strip()
        return {
            "access_token": access,
            "refresh_token": (tokens.get("refresh_token") or data.get("refresh_token")
                              or data.get("refresh") or "").strip(),
            "id_token": idt,
            "account_id": (tokens.get("account_id") or data.get("account_id")
                           or data.get("accountId") or account_id_from(access, idt)),
            "expires_at": tokens.get("expires_at") or data.get("expires_at") or 0,
            "path": p,
        }
    return None


def save_auth(tokens: dict, path: str | None = None) -> dict:
    with _auth_lock:
        return _save_auth_unlocked(tokens, path)

def _save_auth_unlocked(tokens: dict, path: str | None = None) -> dict:
    path = path or AUTH_PATH
    parent = os.path.dirname(os.path.abspath(path))
    os.makedirs(parent, exist_ok=True)
    access = tokens.get("access_token") or ""
    idt = tokens.get("id_token") or ""
    out = {
        "access_token": access,
        "refresh_token": tokens.get("refresh_token") or "",
        "id_token": idt,
        "account_id": tokens.get("account_id") or account_id_from(access, idt),
        "expires_at": int(time.time()) + int(tokens.get("expires_in") or 3600),
        "updated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
    }
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf8") as f:
        json.dump(out, f, indent=2)
        f.flush()
        try:
            os.fsync(f.fileno())
        except OSError:
            pass
    try:
        os.chmod(tmp, 0o600)
    except OSError:
        pass
    os.replace(tmp, path)
    return out


def _post_form(url: str, fields: dict) -> dict:
    data = urllib.parse.urlencode(fields).encode()
    req = urllib.request.Request(
        url, data=data, method="POST",
        headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.loads(r.read().decode())


def refresh_token(refresh: str) -> dict:
    body = _post_form(TOKEN_URL, {
        "grant_type": "refresh_token",
        "client_id": CLIENT_ID,
        "refresh_token": refresh,
    })
    if not body.get("access_token"):
        raise ProxyError(401, body, login=True)
    if not body.get("refresh_token"):
        body["refresh_token"] = refresh
    return body


def _auth_expiring(auth: dict, margin: int = 300) -> bool:
    now = time.time() + margin
    claims = _jwt_claims(auth.get("access_token") or "")
    exp = claims.get("exp")
    if isinstance(exp, (int, float)):
        return exp < now
    try:
        return float(auth.get("expires_at") or 0) < now
    except (TypeError, ValueError):
        return True


def ensure_auth(force_refresh: bool = False, previous_access: str | None = None) -> dict:
    # The entire read/check/refresh/write transaction is protected.  In particular,
    # only one thread can use a rotating refresh token at a time.
    with _auth_lock:
        auth = _load_auth_unlocked()
        if not auth:
            raise ProxyError(401, {"type": "authentication_error", "message": "No tokens"}, login=True)
        # A concurrent request may have refreshed the rejected access token already.
        if force_refresh and previous_access is not None and auth["access_token"] != previous_access:
            return auth
        if not force_refresh and not _auth_expiring(auth):
            return auth
        if not auth.get("refresh_token"):
            raise ProxyError(401, {"type": "authentication_error",
                                  "message": "Access token needs refresh but no refresh_token"}, login=True)
        try:
            body = refresh_token(auth["refresh_token"])
        except urllib.error.HTTPError as e:
            raise _http_error(e, login=e.code in (400, 401, 403)) from e
        except (urllib.error.URLError, OSError) as e:
            raise ProxyError(502, {"type": "auth_transport_error", "message": str(e)}) from e
        if not body.get("id_token") and auth.get("id_token"):
            body["id_token"] = auth["id_token"]
        if not body.get("account_id") and auth.get("account_id"):
            body["account_id"] = auth["account_id"]
        auth = _save_auth_unlocked(body)
        print("[codex_proxy] refreshed access token", flush=True)
        return auth


def _auth_headers(auth: dict, *, stream: bool = False, session_id: str = "") -> dict:
    h = {
        "Authorization": f"Bearer {auth['access_token']}",
        "Content-Type": "application/json",
        "originator": ORIGINATOR,
        "User-Agent": USER_AGENT,
        "Accept": "text/event-stream" if stream else "application/json",
    }
    if auth.get("account_id"):
        h["ChatGPT-Account-ID"] = auth["account_id"]
    if session_id:
        h["session-id"] = session_id
    residency = residency_from(auth.get("access_token") or "")
    if residency:
        h["x-openai-internal-codex-residency"] = residency
    return h


def _extract_model_ids(payload) -> list[str]:
    """Parse Codex /models JSON into a sorted list of model id/slug strings."""
    items = []
    if isinstance(payload, list):
        items = payload
    elif isinstance(payload, dict):
        for key in ("models", "data", "items"):
            if isinstance(payload.get(key), list):
                items = payload[key]
                break
        else:
            # single nested object
            if "slug" in payload or "id" in payload:
                items = [payload]
    ids: list[str] = []
    seen: set[str] = set()
    for it in items:
        if isinstance(it, str):
            mid = it.strip()
        elif isinstance(it, dict):
            mid = (it.get("slug") or it.get("id") or it.get("name") or "").strip()
            # skip hidden models when the catalog marks them
            vis = it.get("visibility")
            if vis is not None and str(vis).lower() in ("hidden", "none", "false"):
                continue
        else:
            continue
        if mid and mid not in seen:
            seen.add(mid)
            ids.append(mid)
    return sorted(ids)


def fetch_available_models(force: bool = False) -> list[str]:
    """Query https://chatgpt.com/backend-api/codex/models for this account's catalog."""
    global _models_cache, _models_cache_at
    now = time.time()
    if not force and _models_cache and (now - _models_cache_at) < _MODELS_CACHE_TTL:
        return list(_models_cache)
    auth = ensure_auth()
    urls = [
        CODEX_MODELS_URL,
        CODEX_MODELS_URL + "?client_version=0.0.0",
    ]
    last_err = None
    for url in urls:
        try:
            req = urllib.request.Request(url, headers=_auth_headers(auth), method="GET")
            with urllib.request.urlopen(req, timeout=30) as r:
                raw = r.read().decode("utf8", "replace")
            payload = json.loads(raw)
            ids = _extract_model_ids(payload)
            if ids:
                _models_cache = ids
                _models_cache_at = now
                print(f"[codex_proxy] fetched {len(ids)} models from {url}", flush=True)
                return list(ids)
            last_err = f"empty catalog from {url}: {raw[:200]}"
        except Exception as e:
            last_err = str(e)
            print(f"[codex_proxy] models fetch failed ({url}): {e}", flush=True)
    if _models_cache:
        print(f"[codex_proxy] using stale model cache ({len(_models_cache)}); last error: {last_err}",
              flush=True)
        return list(_models_cache)
    raise RuntimeError(f"Could not fetch Codex models: {last_err}")


def _parse_callback_query(query: str) -> tuple[str | None, str | None, str | None]:
    """Return (code, state, error) from a query string or full redirect URL."""
    if "://" in query or query.startswith("/"):
        query = urllib.parse.urlparse(query).query
    q = urllib.parse.parse_qs(query)
    code = (q.get("code") or [None])[0]
    st = (q.get("state") or [None])[0]
    err = None
    if q.get("error"):
        err = (q.get("error_description") or q["error"])[0]
    return code, st, err


def _exchange_code(code: str, verifier: str) -> dict:
    body = _post_form(TOKEN_URL, {
        "grant_type": "authorization_code",
        "client_id": CLIENT_ID,
        "code": code,
        "redirect_uri": REDIRECT,
        "code_verifier": verifier,
    })
    if not body.get("access_token"):
        raise RuntimeError(f"token exchange failed: {body}")
    return save_auth(body)


def oauth_login(timeout: int = 300) -> dict:
    """PKCE login with a real callback server + manual paste fallback.

    OpenAI redirects to http://localhost:1455/auth/callback?code=…&state=…
    After workspace selection the browser must hit that URL on *this* machine.
    If the page spins (WSL/SSH/remote), copy the address bar URL and paste it here.
    """
    verifier = secrets.token_urlsafe(64)
    challenge = base64.urlsafe_b64encode(
        hashlib.sha256(verifier.encode("ascii")).digest()
    ).decode("ascii").rstrip("=")
    state = secrets.token_urlsafe(16)
    params = {
        "response_type": "code",
        "client_id": CLIENT_ID,
        "redirect_uri": REDIRECT,
        "scope": SCOPE,
        "code_challenge": challenge,
        "code_challenge_method": "S256",
        "state": state,
        "id_token_add_organizations": "true",
        "codex_cli_simplified_flow": "true",
        "originator": ORIGINATOR,
    }
    url = AUTH_URL + "?" + urllib.parse.urlencode(params)
    result: dict[str, Any] = {"code": None, "state": None, "error": None}
    done = threading.Event()

    class Handler(http.server.BaseHTTPRequestHandler):
        def log_message(self, fmt, *args):
            sys.stderr.write("[oauth-callback] " + (fmt % args) + "\n")

        def _reply(self, html: bytes, code: int = 200):
            self.send_response(code)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(html)))
            self.send_header("Connection", "close")
            self.end_headers()
            self.wfile.write(html)

        def do_GET(self):
            parsed = urllib.parse.urlparse(self.path)
            path = parsed.path.rstrip("/") or "/"
            # Favicon / stray probes must not finish the flow
            if path not in ("/auth/callback", "/callback", "/"):
                if "code=" not in (parsed.query or ""):
                    self._reply(b"ok", 200)
                    return
            code, st, err = _parse_callback_query(parsed.query)
            print(f"[oauth-callback] path={path!r} code={'yes' if code else 'no'} "
                  f"state_match={st == state} error={err!r}", flush=True)
            if err:
                result["error"] = err
                self._reply(b"<html><body><h2>Login failed</h2><pre>"
                            + err.encode("utf8", "replace") + b"</pre></body></html>")
                done.set()
                return
            if not code:
                # Landing without code (e.g. GET /) — keep waiting
                self._reply(b"<html><body><p>Waiting for OAuth redirect...</p></body></html>")
                return
            result["code"] = code
            result["state"] = st
            self._reply(
                b"<html><body style='font-family:sans-serif'>"
                b"<h2>codex_proxy login complete</h2>"
                b"<p>You can close this tab and return to the terminal.</p>"
                b"</body></html>"
            )
            done.set()

        def do_HEAD(self):
            self.send_response(200)
            self.end_headers()

    # Prefer dual-stack when available so localhost → ::1 still hits us
    httpd = None
    last_err = None
    # OAuth callback must remain loopback-only.
    for bind_host in ("127.0.0.1", "localhost"):
        try:
            httpd = http.server.ThreadingHTTPServer((bind_host, 1455), Handler)
            httpd.allow_reuse_address = True
            print(f"[oauth] callback listening on http://{bind_host}:1455/auth/callback", flush=True)
            break
        except OSError as e:
            last_err = e
            httpd = None
    if httpd is None:
        raise RuntimeError(
            f"Port 1455 busy or unbindable ({last_err}). "
            "Stop other Codex/OpenCode login servers, or paste the redirect URL manually when prompted."
        )

    def serve():
        while not done.is_set():
            httpd.timeout = 0.5
            try:
                httpd.handle_request()
            except Exception as e:
                if not done.is_set():
                    print(f"[oauth] serve error: {e}", flush=True)

    threading.Thread(target=serve, daemon=True).start()

    print("\n=== Codex OAuth ===", flush=True)
    print("1. Browser should open. Sign in and select your workspace.", flush=True)
    print("2. You should land on http://localhost:1455/auth/callback?code=…", flush=True)
    print("3. If the browser spins or shows connection refused, copy the FULL", flush=True)
    print("   URL from the address bar and paste it below, then press Enter.", flush=True)
    print(f"\nAuth URL:\n{url}\n", flush=True)
    try:
        webbrowser.open(url)
    except Exception:
        pass

    def wait_for_paste():
        # stdin paste races the HTTP callback; whichever finishes first wins
        try:
            line = input("Paste redirect URL (or press Enter to wait for browser):\n> ").strip()
        except EOFError:
            return
        if not line or done.is_set():
            return
        code, st, err = _parse_callback_query(line)
        if err:
            result["error"] = err
            done.set()
            return
        if code:
            if st != state:
                result["error"] = "OAuth state mismatch in pasted redirect URL"
                done.set()
                return
            result["code"] = code
            result["state"] = st
            print("[oauth] accepted pasted redirect URL", flush=True)
            done.set()
        else:
            print("[oauth] no code= in that input; still waiting for browser…", flush=True)

    paste_thread = threading.Thread(target=wait_for_paste, daemon=True)
    paste_thread.start()

    if not done.wait(timeout):
        try:
            httpd.server_close()
        except Exception:
            pass
        raise TimeoutError(
            "OAuth timed out — callback never received.\n"
            "Common causes: WSL/SSH (browser is on another host), port 1455 blocked,\n"
            "or another app holding 1455. Re-run and paste the redirect URL, or run login\n"
            "on the same machine as the browser."
        )
    try:
        httpd.server_close()
    except Exception:
        pass

    if result["error"]:
        raise RuntimeError(result["error"])
    if not result["code"]:
        raise RuntimeError("OAuth finished without an authorization code")
    if result["state"] and result["state"] != state:
        raise RuntimeError(
            f"OAuth state mismatch (got {result['state']!r}, expected {state!r}). "
            "Another login may be using port 1455."
        )
    print("[oauth] exchanging code for tokens…", flush=True)
    return _exchange_code(result["code"], verifier)


# ---------------------------------------------------------------------------
# Chat ↔ Responses translation
# ---------------------------------------------------------------------------

def _text(content) -> str:
    if content is None:
        return ""
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        parts = []
        for p in content:
            if isinstance(p, dict):
                parts.append(p.get("text") or "")
            else:
                parts.append(str(p))
        return "".join(parts)
    return str(content)


def _input_content(content):
    """Translate Chat content parts without discarding image inputs."""
    if not isinstance(content, list):
        return _text(content)
    parts = []
    for part in content:
        if not isinstance(part, dict):
            parts.append({"type": "input_text", "text": str(part)})
        elif part.get("type") in ("text", "input_text"):
            parts.append({"type": "input_text", "text": part.get("text") or ""})
        elif part.get("type") == "image_url":
            image = part.get("image_url")
            if isinstance(image, str): image = {"url": image}
            if not isinstance(image, dict) or not image.get("url"):
                raise ValueError("Image content requires an image_url URL")
            converted = {"type": "input_image", "image_url": image["url"]}
            if image.get("detail"): converted["detail"] = image["detail"]
            parts.append(converted)
        elif part.get("type") == "input_image":
            parts.append(dict(part))
        else:
            raise ValueError(f"Unsupported input content type: {part.get('type')}")
    return parts


def chat_to_responses(body: dict) -> dict:
    instructions = None
    items = []
    for m in body.get("messages") or []:
        role = m.get("role")
        if role == "system":
            t = _text(m.get("content"))
            if t:
                instructions = f"{instructions}\n\n{t}" if instructions else t
        elif role == "user":
            items.append({"role": "user", "content": _input_content(m.get("content"))})
        elif role == "assistant":
            t = _text(m.get("content"))
            if t:
                items.append({"role": "assistant", "content": t})
            for tc in m.get("tool_calls") or []:
                fn = tc.get("function") or {}
                items.append({
                    "type": "function_call",
                    "call_id": tc.get("id") or "",
                    "name": fn.get("name") or "",
                    "arguments": fn.get("arguments") or "{}",
                })
        elif role == "tool":
            content = _input_content(m.get("content"))
            items.append({
                "type": "function_call_output",
                "call_id": m.get("tool_call_id") or "",
                "output": _text(m.get("content")),
            })
            # Function outputs are text in Codex. Supply tool-returned images as
            # the following user input, after preserving the tool-call result.
            if isinstance(content, list):
                images = [part for part in content if part["type"] == "input_image"]
                if images: items.append({"role": "user", "content": images})
    out: dict[str, Any] = {
        "model": body.get("model"),
        "input": items,
        "stream": True,
        "store": False,
    }
    if instructions:
        out["instructions"] = instructions
    tools = body.get("tools") or []
    if tools:
        rtools = []
        for t in tools:
            if t.get("type") == "function" and "function" in t:
                fn = t["function"]
                rtools.append({
                    "type": "function",
                    "name": fn.get("name", ""),
                    "description": fn.get("description") or "",
                    "parameters": fn.get("parameters") or {"type": "object", "properties": {}},
                })
            elif t.get("type") == "function" and "name" in t:
                rtools.append(t)
        if rtools:
            out["tools"] = rtools
            out["tool_choice"] = body.get("tool_choice") or "auto"
            out["parallel_tool_calls"] = True
    return out


def sse_line(obj: dict) -> bytes:
    return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n".encode("utf-8")


def _emit_text(wfile, model: str, text: str):
    if not text:
        return
    wfile.write(sse_line({
        "id": "chatcmpl-proxy",
        "object": "chat.completion.chunk",
        "model": model,
        "choices": [{"index": 0, "delta": {"content": text}, "finish_reason": None}],
    }))
    wfile.flush()


def _emit_done(wfile, model: str, finish: str, usage: dict | None = None):
    chunk = {
        "id": "chatcmpl-proxy",
        "object": "chat.completion.chunk",
        "model": model,
        "choices": [{"index": 0, "delta": {}, "finish_reason": finish}],
    }
    if usage:
        chunk["usage"] = usage
    wfile.write(sse_line(chunk))
    wfile.write(b"data: [DONE]\n\n")
    wfile.flush()


def open_codex_stream(codex_body: dict, auth: dict):
    session_id = str(uuid.uuid4())
    data = json.dumps(codex_body).encode()
    print(f"[codex] → model={codex_body.get('model')} account={auth.get('account_id')!r} "
          f"tools={len(codex_body.get('tools') or [])} input_items={len(codex_body.get('input') or [])}",
          flush=True)
    # Retry only an initial 401, before any stream or tool output exists.
    for attempt in range(2):
        headers = _auth_headers(auth, stream=True, session_id=session_id)
        # CODEX_URL is intentionally the ChatGPT Codex Responses endpoint, never the
        # generic api.openai.com Responses endpoint.
        req = urllib.request.Request(CODEX_URL, data, headers, method="POST")
        try:
            return urllib.request.urlopen(req, timeout=600)
        except urllib.error.HTTPError as e:
            error = _http_error(e, login=attempt == 1 and e.code == 401)
            if e.code != 401 or attempt:
                raise error from e
            auth = ensure_auth(force_refresh=True, previous_access=auth["access_token"])
        except (urllib.error.URLError, OSError) as e:
            raise ProxyError(502, {"type": "upstream_transport_error", "message": str(e)}) from e


def stream_codex_as_chat(codex_body: dict, upstream, wfile, model: str):
    # Role message for agent.py (expects assistant role on first chunk sometimes)
    wfile.write(sse_line({
        "id": "chatcmpl-proxy",
        "object": "chat.completion.chunk",
        "model": model,
        "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}],
    }))
    wfile.flush()

    content = ""
    calls: dict[int, dict] = {}
    call_index: dict[str, int] = {}
    usage: dict = {}
    seen_types: list[str] = []
    completed = False

    try:
        with upstream as r:
            print(f"[codex] ← HTTP {getattr(r, 'status', 200)}", flush=True)
            for raw in r:
                line = raw.decode("utf8", "replace").rstrip()
                if not line:
                    continue
                # Some gateways send "event: foo" then "data: {...}"
                if line.startswith("event:"):
                    continue
                if line.startswith("data:"):
                    payload = line[5:].lstrip()
                else:
                    # bare JSON line
                    payload = line
                if payload == "[DONE]":
                    break
                try:
                    ev = json.loads(payload)
                except json.JSONDecodeError:
                    continue
                if not isinstance(ev, dict):
                    continue
                et = ev.get("type") or ""
                if et and et not in seen_types:
                    seen_types.append(et)
                    print(f"[codex] event {et}", flush=True)

                if et in ("response.output_text.delta", "response.content_part.delta"):
                    delta = ev.get("delta") or ""
                    if isinstance(delta, dict):
                        delta = delta.get("text") or delta.get("content") or ""
                    content += delta
                    _emit_text(wfile, model, delta)
                elif et == "response.output_text.done":
                    # full text if deltas were skipped
                    full = ev.get("text") or ""
                    if full and not content:
                        content = full
                        _emit_text(wfile, model, full)
                elif et == "response.output_item.added":
                    item = ev.get("item") or {}
                    if item.get("type") == "function_call":
                        idx = len(calls)
                        cid = item.get("call_id") or item.get("id") or f"call_{idx}"
                        call_index[item.get("id") or cid] = idx
                        call_index[cid] = idx
                        name = item.get("name") or ""
                        calls[idx] = {
                            "id": cid, "type": "function",
                            "function": {"name": name, "arguments": item.get("arguments") or ""},
                        }
                    elif item.get("type") == "message":
                        for part in item.get("content") or []:
                            if part.get("type") in ("output_text", "text") and part.get("text"):
                                if not content:
                                    content += part["text"]
                                    _emit_text(wfile, model, part["text"])
                elif et == "response.function_call_arguments.delta":
                    item_id = ev.get("item_id") or ""
                    idx = call_index.get(item_id)
                    if idx is not None and idx in calls:
                        calls[idx]["function"]["arguments"] += ev.get("delta") or ""
                elif et == "response.function_call_arguments.done":
                    item_id = ev.get("item_id") or ""
                    idx = call_index.get(item_id)
                    if idx is not None and idx in calls:
                        if ev.get("arguments") is not None:
                            calls[idx]["function"]["arguments"] = ev["arguments"]
                        if ev.get("name"):
                            calls[idx]["function"]["name"] = ev["name"]
                elif et == "response.output_item.done":
                    item = ev.get("item") or {}
                    if item.get("type") == "function_call":
                        cid = item.get("call_id") or item.get("id") or ""
                        idx = call_index.get(item.get("id") or cid)
                        if idx is None:
                            idx = len(calls)
                            call_index[item.get("id") or cid] = idx
                            call_index[cid] = idx
                            calls[idx] = {"id": cid, "type": "function",
                                          "function": {"name": "", "arguments": ""}}
                        if item.get("name"):
                            calls[idx]["function"]["name"] = item["name"]
                        if item.get("arguments") is not None:
                            calls[idx]["function"]["arguments"] = item["arguments"]
                        if item.get("call_id"):
                            calls[idx]["id"] = item["call_id"]
                    elif item.get("type") == "message":
                        for part in item.get("content") or []:
                            if part.get("type") in ("output_text", "text") and part.get("text"):
                                if part["text"] not in content:
                                    content += part["text"]
                                    _emit_text(wfile, model, part["text"])
                elif et == "response.completed":
                    completed = True
                    resp = ev.get("response") or {}
                    if "usage" in resp:
                        u = resp["usage"]
                        usage = {
                            "prompt_tokens": u.get("input_tokens", 0),
                            "completion_tokens": u.get("output_tokens", 0),
                            "total_tokens": u.get("total_tokens", 0),
                        }
                    # The completed response is authoritative, including when earlier
                    # function-call events or argument deltas were missing.
                    for item in resp.get("output") or []:
                        if item.get("type") == "function_call":
                            cid = item.get("call_id") or item.get("id") or ""
                            idx = call_index.get(item.get("id"))
                            if idx is None:
                                idx = call_index.get(cid)
                            if idx is None:
                                idx = len(calls)
                                calls[idx] = {"id": cid or f"call_{idx}", "type": "function",
                                              "function": {"name": "", "arguments": ""}}
                            if item.get("id"):
                                call_index[item["id"]] = idx
                            if cid:
                                call_index[cid] = idx
                            if item.get("call_id"):
                                calls[idx]["id"] = item["call_id"]
                            if item.get("name") is not None:
                                calls[idx]["function"]["name"] = item["name"]
                            if item.get("arguments") is not None:
                                calls[idx]["function"]["arguments"] = item["arguments"]
                        elif item.get("type") == "message" and not content:
                            for part in item.get("content") or []:
                                if part.get("type") in ("output_text", "text"):
                                    t = part.get("text") or ""
                                    content += t
                                    _emit_text(wfile, model, t)
                elif et in ("response.failed", "response.incomplete", "error"):
                    resp = ev.get("response") or {}
                    err = resp.get("error") or ev.get("error") or resp.get("incomplete_details") or ev
                    raise ProxyError(502, err, login=_requires_login(err))
    except ProxyError:
        raise
    except urllib.error.HTTPError as e:
        raise _http_error(e) from e
    except Exception as e:
        raise ProxyError(502, {"type": "upstream_stream_error", "message": str(e)}) from e

    if not completed:
        raise ProxyError(502, {"type": "upstream_stream_error",
                              "message": "Upstream stream ended before response.completed"})
    if not content and not calls:
        raise ProxyError(502, {"type": "upstream_stream_error",
                              "message": "Empty upstream response"})

    # Send each call exactly once, fully populated. Streaming partial tool arguments
    # cannot represent corrections from Responses' authoritative done events.
    for idx in sorted(calls):
        tc = calls[idx]
        args = tc["function"]["arguments"]
        if not tc["id"] or not tc["function"]["name"] or not isinstance(args, str):
            raise ProxyError(502, {"type": "invalid_tool_call",
                                   "message": f"Incomplete upstream tool call at index {idx}"})
        try:
            if not isinstance(json.loads(args), dict):
                raise ValueError("arguments must be an object")
        except (ValueError, TypeError) as e:
            raise ProxyError(502, {"type": "invalid_tool_call",
                                   "message": f"Invalid tool arguments for {tc['function']['name']}: {e}"}) from e
    for idx in sorted(calls):
        tc = calls[idx]
        wfile.write(sse_line({
            "id": "chatcmpl-proxy",
            "object": "chat.completion.chunk",
            "model": model,
            "choices": [{"index": 0, "delta": {"tool_calls": [{
                "index": idx, "id": tc["id"], "type": "function",
                "function": dict(tc["function"]),
            }]}, "finish_reason": None}],
        }))
        wfile.flush()

    print(f"[codex] done content_len={len(content)} tool_calls={len(calls)} usage={usage}",
          flush=True)
    _emit_done(wfile, model, "tool_calls" if calls else "stop", usage or None)


# ---------------------------------------------------------------------------
# HTTP server
# ---------------------------------------------------------------------------

class Handler(http.server.BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, fmt, *args):
        sys.stderr.write("[codex_proxy] " + (fmt % args) + "\n")

    def _read_json(self) -> dict:
        n = int(self.headers.get("Content-Length") or 0)
        raw = self.rfile.read(n) if n else b"{}"
        return json.loads(raw.decode("utf8") or "{}")

    def _send(self, code: int, body: bytes, content_type: str = "application/json"):
        self.send_response(code)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Access-Control-Allow-Origin", "*")
        self.end_headers()
        self.wfile.write(body)

    def do_OPTIONS(self):
        self.send_response(204)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
        self.send_header("Access-Control-Allow-Headers", "*")
        self.end_headers()

    def do_GET(self):
        path = urllib.parse.urlparse(self.path).path.rstrip("/") or "/"
        if path in ("/health", "/v1/health"):
            self._send(200, json.dumps({"ok": True, "pid": os.getpid()}).encode())
        elif path in ("/props", "/v1/props"):
            # llama-server–style props; agent.py uses n_ctx for context_size
            props = {
                "n_ctx": CONTEXT_LENGTH,
                "default_generation_settings": {"n_ctx": CONTEXT_LENGTH},
            }
            self._send(200, json.dumps(props).encode())
        elif path in ("/v1/models", "/models"):
            try:
                ids = fetch_available_models()
            except Exception as e:
                err = json.dumps({"error": {"message": str(e), "type": "models_error"}}).encode()
                self._send(502, err)
                return
            models = {
                "object": "list",
                "data": [
                    {
                        "id": m,
                        "object": "model",
                        "owned_by": "openai",
                        "context_length": CONTEXT_LENGTH,
                        "top_provider": {"context_length": CONTEXT_LENGTH},
                    }
                    for m in ids
                ],
            }
            self._send(200, json.dumps(models).encode())
        else:
            self._send(404, b'{"error":"not found"}')

    def do_POST(self):
        path = urllib.parse.urlparse(self.path).path.rstrip("/") or "/"
        if path not in ("/v1/chat/completions", "/chat/completions"):
            self._send(404, b'{"error":"not found"}')
            return
        started = False
        try:
            body = self._read_json()
            codex_body = chat_to_responses(body)
            model = body.get("model")
            # Authenticate independently; concurrent upstream streams are permitted.
            auth = ensure_auth()
            with open_codex_stream(codex_body, auth) as upstream:
                self.close_connection = True
                self.send_response(200)
                self.send_header("Content-Type", "text/event-stream; charset=utf-8")
                self.send_header("Cache-Control", "no-cache")
                self.send_header("Access-Control-Allow-Origin", "*")
                self.send_header("Connection", "close")
                started = True
                self.end_headers()
                stream_codex_as_chat(codex_body, upstream, self.wfile, model)
        except Exception as e:
            error = e if isinstance(e, ProxyError) else ProxyError(500, {
                "message": str(e), "type": "proxy_error"})
            try:
                if started:
                    # HTTP status is already committed. Abort the stream; do not synthesize
                    # an SSE error that could be mistaken for model output.
                    self.close_connection = True
                    try:
                        self.connection.shutdown(2)
                    except OSError:
                        pass
                    self.connection.close()
                else:
                    self._send(error.status, json.dumps({"error": error.error}).encode())
            except Exception:
                pass


def main(argv=None):
    global AUTH_PATH
    ap = argparse.ArgumentParser(description="Chat Completions → Codex Responses proxy")
    ap.add_argument("--host", default=HOST)
    ap.add_argument("--port", type=int, default=PORT)
    ap.add_argument("--login", action="store_true", help="OAuth login and exit")
    ap.add_argument("--auth-file", default=AUTH_PATH)
    args = ap.parse_args(argv)
    AUTH_PATH = args.auth_file

    if args.login:
        auth = oauth_login()
        print(f"Saved tokens to {AUTH_PATH}")
        print(f"account={auth.get('account_id')}")
        return

    if not load_auth():
        print("No tokens found. Run: python3 codex_proxy.py --login", file=sys.stderr)
        sys.exit(1)

    class QuietServer(http.server.ThreadingHTTPServer):
        allow_reuse_address = True

    server = QuietServer((args.host, args.port), Handler)
    print(f"codex_proxy listening on http://{args.host}:{args.port}/v1")
    print(f"auth file: {AUTH_PATH}")
    print("agent.py:")
    print("  /set api http://127.0.0.1:%d/v1" % args.port)
    print("  /set api_key dummy")
    try:
        ids = fetch_available_models(force=True)
        print(f"  # {len(ids)} models from Codex catalog:")
        for m in ids:
            print(f"  /set model {m}")
    except Exception as e:
        print(f"  # could not list models: {e}")
        print("  # retry: curl http://127.0.0.1:%d/v1/models" % args.port)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\nbye")

if __name__ == "__main__":
    args = sys.argv[1:]
    if "--just-proxy" in args:
        args = [arg for arg in args if arg != "--just-proxy"]
    main(args)
