#!/usr/bin/env python3
"""yugos: run Claude Code, Codex, pi or opencode through Yugos with your project key.

  yugos claude [client arguments]
  yugos codex [client arguments]
  yugos pi [client arguments]
  yugos opencode [client arguments]
  yugos check

Requires Python 3.11+. The installer at /install.sh puts this script on your
PATH as yugos. Options before the client's own arguments: --env staging (or
YUGOS_ENV) selects the staging API, and --env-file PATH reads the key from a
specific file. Otherwise the key comes from YUGOS_API_KEY or the nearest .env
in this folder or one above it.

Claude Code, Codex and opencode are configured for this process only, through
CLI overrides and environment variables. pi reads custom providers only from its
models.json, so "yugos pi" adds or refreshes one "yugos" provider there and
leaves every other entry unchanged.
"""

import argparse
import json
import os
from pathlib import Path
import re
import shlex
import shutil
import sys
import subprocess
import tempfile
import urllib.error
import urllib.parse
import urllib.request

KEY_NAMES = ("YUGOS_API_KEY", "YUGO_API_KEY")
ORIGINS = {"production": "https://api.yugos.ai", "staging": "https://staging-api.yugos.ai"}
DEFAULT_ORIGIN = ORIGINS["production"]
CLAUDE_CONTEXT_TOKENS = "1000000"
# Claude Code's auto-mode classifier picks its own model. The environment
# variables cover current versions; the mapped IDs cover earlier ones.
CLAUDE_CLASSIFIER_ENV = ("CLAUDE_CODE_AUTO_MODE_MODEL", "CLAUDE_CODE_BG_CLASSIFIER_MODEL")
CLAUDE_CLASSIFIER_MODELS = ("claude-sonnet-5", "claude-opus-4-8")
# Codex features that would push Yugos past its 128-tool limit or its wire format.
CODEX_DISABLED_FEATURES = ("enable_request_compression", "apps", "plugins", "multi_agent", "goals")
# Client versions the last compatibility check used; keep in step with the
# setup page (src/components/client-setup.tsx).
TESTED_VERSIONS = {"claude": "2.1.281", "codex": "0.157.1", "pi": "1.4.0", "opencode": "1.19.5"}
CLIENT_NAMES = {"claude": "Claude Code", "codex": "Codex", "pi": "pi", "opencode": "opencode"}
PI_PROVIDER = "yugos"
PI_MAX_OUTPUT_TOKENS = 65536
OPENCODE_PROVIDER = "yugos"


def file_key(path):
    """Read only Yugos key declarations; never execute a dotenv file."""
    values = {}
    errors = {}
    for line in path.read_text().splitlines():
        match = re.match(r"^\s*(?:export\s+)?(YUGOS?_API_KEY)\s*=\s*(.*)$", line)
        if not match:
            continue
        name = match.group(1)
        values[name] = None
        try:
            parts = shlex.split(match.group(2), comments=True, posix=True)
        except ValueError:
            errors[name] = f"Invalid quoted {name} in {path}"
            continue
        if len(parts) != 1 or not parts[0] or parts[0].startswith("$"):
            errors[name] = f"Set a single nonempty {name} in {path}; variable interpolation is not expanded"
            continue
        values[name] = parts[0]
        errors.pop(name, None)
    key = next((values[name] for name in KEY_NAMES if values.get(name)), None)
    if key:
        return key
    if errors:
        raise ValueError(next(errors[name] for name in KEY_NAMES if name in errors))
    return None


def read_key(env, cwd, env_file=None):
    if env_file:
        path = Path(env_file).expanduser().resolve()
        key = file_key(path)
        if key:
            return key, str(path)
        raise ValueError(f"No YUGOS_API_KEY found in {path}")
    for name in KEY_NAMES:
        if env.get(name):
            return env[name], name
    for directory in (cwd, *cwd.parents):
        path = directory / ".env"
        if path.is_file():
            key = file_key(path)
            if key:
                return key, str(path)
    raise ValueError(
        "Set YUGOS_API_KEY in your environment or a project .env file, "
        "or select a file with --env-file PATH."
    )


def api_origin(env, environment=None):
    """YUGOS_API_ORIGIN, else the selected environment's API (--env or YUGOS_ENV)."""
    selected = environment or env.get("YUGOS_ENV") or "production"
    if selected not in ORIGINS:
        raise ValueError(f"Choose an environment from: {', '.join(ORIGINS)}")
    origin = env.get("YUGOS_API_ORIGIN", ORIGINS[selected]).rstrip("/")
    parsed = urllib.parse.urlsplit(origin)
    if (
        parsed.scheme not in ("https", "http") or not parsed.netloc
        or parsed.path or parsed.query or parsed.fragment
        or parsed.username or parsed.password
    ):
        raise ValueError("YUGOS_API_ORIGIN must be an origin such as https://api.yugos.ai (without /v1)")
    if parsed.scheme != "https" and parsed.hostname not in ("localhost", "127.0.0.1", "::1"):
        raise ValueError("YUGOS_API_ORIGIN must use HTTPS, except for loopback tests")
    return origin


def codex_overrides(env, args, origin):
    # Hosted web search and reasoning summaries are served by Yugos. App
    # connectors, plugins and multi-agent tools would exceed its 128-tool limit.
    values = {
        "model": "yugos", "model_provider": "yugos",
        **{f"features.{name}": False for name in CODEX_DISABLED_FEATURES},
        "model_providers.yugos.name": "Yugos API",
        "model_providers.yugos.base_url": origin + "/v1",
        "model_providers.yugos.env_key": "YUGOS_API_KEY",
        "model_providers.yugos.wire_api": "responses",
        "model_providers.yugos.requires_openai_auth": False,
        "model_providers.yugos.supports_websockets": False,
        "model_providers.yugos.request_max_retries": 0,
        "model_providers.yugos.stream_max_retries": 0,
    }
    mcp_overrides = []
    # Preserve normal sandbox settings while disabling inherited MCP servers.
    if "--ignore-user-config" not in args:
        config_home = Path(env.get("CODEX_HOME", str(Path.home() / ".codex")))
        path = config_home / "config.toml"
        if path.is_file():
            import tomllib  # Only Codex needs it.
            try:
                config = tomllib.loads(path.read_text())
            except tomllib.TOMLDecodeError as error:
                raise ValueError(f"{path} is not valid TOML ({error}); fix it before using yugos codex") from None
            names = config.get("mcp_servers", {})
            if names:
                # A TOML table preserves literal server names, including dots.
                disabled = ", ".join(f"{json.dumps(name)} = {{ enabled = false }}" for name in names)
                mcp_overrides.append("mcp_servers={" + disabled + "}")
    return [f"{name}={json.dumps(value)}" for name, value in values.items()] + mcp_overrides


def warn_missing_codex_features(executable):
    """Codex ignores unknown --config keys, so say when a disabled feature was renamed."""
    try:
        listed = subprocess.run(
            [executable, "features", "list"], capture_output=True, text=True, timeout=10, check=True,
        ).stdout
    except (OSError, subprocess.SubprocessError):
        return
    known = {line.split()[0] for line in listed.splitlines() if line.strip()}
    missing = [name for name in CODEX_DISABLED_FEATURES if name not in known]
    if known and missing:
        print(
            f"yugos: this Codex version has no feature {', '.join(missing)}; yugos may not "
            "be able to turn off everything it needs to. Update yugos (rerun the installer).",
            file=sys.stderr,
        )


def version_tuple(text):
    match = re.search(r"\d+(?:\.\d+)+", text or "")
    return tuple(int(part) for part in match.group(0).split(".")) if match else None


def note_untested_version(client, executable, env):
    """Say once per client version when it differs from the one yugos was tested with."""
    try:
        output = subprocess.run(
            [executable, "--version"], capture_output=True, text=True, timeout=10,
        ).stdout
    except (OSError, subprocess.SubprocessError):
        return
    found, tested = version_tuple(output), version_tuple(TESTED_VERSIONS[client])
    if not found or found == tested:
        return
    installed = ".".join(map(str, found))
    home = Path(env.get("HOME") or Path.home())
    state = Path(env.get("XDG_STATE_HOME") or home / ".local" / "state") / "yugos" / "versions-noted"
    entry = f"{client} {installed}"
    try:
        if entry in state.read_text().splitlines():
            return
    except OSError:
        pass
    print(
        f"yugos: {CLIENT_NAMES[client]} {installed} is {'newer' if found > tested else 'older'} than "
        f"{TESTED_VERSIONS[client]}, the version yugos was last tested with. If setup fails, rerun "
        "the installer for the latest yugos. (Shown once for this version.)",
        file=sys.stderr,
    )
    try:
        state.parent.mkdir(parents=True, exist_ok=True)
        with state.open("a") as handle:
            handle.write(entry + "\n")
    except OSError:
        pass


def collect_codex_config(args):
    """Keep overrides at one CLI scope, including those supplied after exec."""
    remaining, overrides = [], []
    i = 0
    while i < len(args):
        arg = args[i]
        if arg == "--":
            remaining.extend(args[i:])
            break
        if arg in ("-c", "--config"):
            if i + 1 == len(args):
                raise ValueError(f"{arg} requires key=value")
            overrides.append(args[i + 1])
            i += 2
            continue
        if arg.startswith("--config="):
            overrides.append(arg.split("=", 1)[1])
        else:
            remaining.append(arg)
        i += 1
    return remaining, overrides


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


def fetch_json(origin, path, key):
    """GET a Yugos API path without following a credential-bearing redirect."""
    request = urllib.request.Request(
        origin + path, headers={"Authorization": "Bearer " + key, "Accept": "application/json"},
    )
    with urllib.request.build_opener(NoRedirect).open(request, timeout=20) as response:
        return json.load(response)


def chat_models(catalog):
    """(id, name, context, max output) for the router, then every Chat-capable catalog model."""
    entries = [("yugos", "Yugos auto", 1000000, PI_MAX_OUTPUT_TOKENS)]
    for model in catalog.get("models", []):
        if model.get("id") == "yugos" or "chat_completions" not in model.get("protocols", []):
            continue
        entries.append((
            model["id"], model.get("name") or model["id"],
            int(model.get("context_tokens") or 200000),
            min(int(model.get("max_output_tokens") or 16384), PI_MAX_OUTPUT_TOKENS),
        ))
    return entries


def pi_models(catalog):
    """pi model entries: the router first, then every Chat-capable catalog model."""
    return [{
        "id": model_id, "name": name, "input": ["text"], "reasoning": False,
        "contextWindow": context, "maxTokens": output,
        "compat": {"maxTokensField": "max_tokens"},
    } for model_id, name, context, output in chat_models(catalog)]


def opencode_config(env, origin, key):
    """Inline opencode config adding a yugos provider; merged over the user's own config."""
    try:
        models = chat_models(fetch_json(origin, "/v1/catalog", key))
    except (urllib.error.URLError, TimeoutError, ValueError, TypeError, KeyError, AttributeError):
        models = chat_models({})
    config = {}
    if env.get("OPENCODE_CONFIG_CONTENT"):
        try:
            config = json.loads(env["OPENCODE_CONFIG_CONTENT"])
        except ValueError:
            raise ValueError("OPENCODE_CONFIG_CONTENT is not valid JSON; fix or unset it before adding Yugos") from None
        if not isinstance(config, dict):
            raise ValueError("OPENCODE_CONFIG_CONTENT is not a JSON object; fix or unset it before adding Yugos")
        if not isinstance(config.get("provider", {}), dict):
            raise ValueError("OPENCODE_CONFIG_CONTENT has a provider that is not an object; fix or unset it before adding Yugos")
    config.setdefault("provider", {})[OPENCODE_PROVIDER] = {
        "npm": "@ai-sdk/openai-compatible", "name": "Yugos",
        # opencode substitutes the key from this process's environment.
        "options": {"baseURL": origin + "/v1", "apiKey": "{env:YUGOS_API_KEY}"},
        "models": {
            model_id: {"name": name, "limit": {"context": context, "output": output}}
            for model_id, name, context, output in models
        },
    }
    # Session titles and summaries use small_model; keep them on Yugos too.
    config.setdefault("model", f"{OPENCODE_PROVIDER}/yugos")
    config.setdefault("small_model", f"{OPENCODE_PROVIDER}/yugos")
    return json.dumps(config)


def configure_pi(env, origin, key):
    """Add or refresh the yugos provider in pi's models.json; keep every other entry."""
    home = Path(env.get("PI_CODING_AGENT_DIR") or Path(env.get("HOME", str(Path.home()))) / ".pi" / "agent")
    path = home / "models.json"
    config = {}
    if path.is_file():
        try:
            config = json.loads(path.read_text())
        except ValueError:
            raise ValueError(f"{path} is not valid JSON; fix it before adding Yugos") from None
        if not isinstance(config, dict) or not isinstance(config.get("providers", {}), dict):
            raise ValueError(f"{path} has no providers object; fix it before adding Yugos")
    providers = config.setdefault("providers", {})
    previous = providers.get(PI_PROVIDER)
    try:
        models = pi_models(fetch_json(origin, "/v1/catalog", key))
    except (urllib.error.URLError, TimeoutError, ValueError, TypeError, KeyError, AttributeError):
        # Keep the last listed models for the same API; otherwise list the router only.
        same_api = isinstance(previous, dict) and previous.get("baseUrl") == origin + "/v1"
        kept = previous.get("models") if same_api else None
        models = kept if isinstance(kept, list) and kept else pi_models({})
    # pi reads this one global provider, so --env staging points it at staging
    # until the next "yugos pi" refreshes it.
    providers[PI_PROVIDER] = {
        "baseUrl": origin + "/v1", "api": "openai-completions",
        # Resolved from this process's environment; the key is never written.
        "apiKey": "$YUGOS_API_KEY", "authHeader": True, "models": models,
    }
    home.mkdir(parents=True, exist_ok=True)
    descriptor, temporary = tempfile.mkstemp(prefix=".models.json.", dir=home)
    try:
        with os.fdopen(descriptor, "w") as handle:
            handle.write(json.dumps(config, indent=2) + "\n")
        os.chmod(temporary, 0o600)
        os.replace(temporary, path)
    except BaseException:
        Path(temporary).unlink(missing_ok=True)
        raise
    return path


def pi_selection(args):
    """Arguments that keep pi on the yugos provider unless the caller picks another."""
    provider = model = None
    for index, arg in enumerate(args):
        for flag in ("--provider", "--model"):
            if arg == flag:
                value = args[index + 1] if index + 1 < len(args) else ""
            elif arg.startswith(flag + "="):
                value = arg[len(flag) + 1:]
            else:
                continue
            if flag == "--provider":
                provider = value
            else:
                model = value
    if provider is None and model is None:
        return ["--provider", PI_PROVIDER, "--model", "yugos"]
    if provider is None and "/" not in model:
        # A bare --model pattern would otherwise match any provider's models.
        return ["--provider", PI_PROVIDER]
    if model is None and provider == PI_PROVIDER:
        return ["--model", "yugos"]
    return []


def build_command(client, args, env=None, cwd=None, env_file=None, environment=None):
    env = dict(os.environ if env is None else env)
    cwd = Path.cwd() if cwd is None else Path(cwd).resolve()
    key, _ = read_key(env, cwd, env_file)
    origin = api_origin(env, environment)
    executable = shutil.which(client, path=env.get("PATH"))
    if not executable:
        raise ValueError(f"Install {client} and make sure it is on PATH before using this launcher")
    env["YUGOS_API_KEY"] = key
    note_untested_version(client, executable, env)
    if client == "codex":
        args, extra_overrides = collect_codex_config(list(args))
        warn_missing_codex_features(executable)
        command = [executable, "--no-daemon"]
        for value in codex_overrides(env, args, origin) + extra_overrides:
            command.extend(["--config", value])
    elif client == "pi":
        configure_pi(env, origin, key)
        command = [executable, *pi_selection(list(args))]
    elif client == "opencode":
        env["OPENCODE_CONFIG_CONTENT"] = opencode_config(env, origin, key)
        command = [executable]
    else:
        for name in (
            "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN",
            "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY",
        ):
            env.pop(name, None)
        env.update({
            "ANTHROPIC_BASE_URL": origin, "ANTHROPIC_AUTH_TOKEN": key,
            "ANTHROPIC_MODEL": "yugos", "ANTHROPIC_DEFAULT_SONNET_MODEL": "yugos",
            "ANTHROPIC_DEFAULT_HAIKU_MODEL": "yugos", "ANTHROPIC_DEFAULT_OPUS_MODEL": "yugos",
            "ANTHROPIC_DEFAULT_FABLE_MODEL": "yugos",
            # Label the routed slots instead of "Custom Opus model".
            **{
                f"ANTHROPIC_DEFAULT_{slot}_MODEL_NAME": "Yugos auto"
                for slot in ("OPUS", "SONNET", "HAIKU", "FABLE")
            },
            "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "CLAUDE_CODE_MAX_RETRIES": "0",
            "CLAUDE_CODE_MAX_OUTPUT_TOKENS": "32000",
            **dict.fromkeys(CLAUDE_CLASSIFIER_ENV, "yugos"),
        })
        env.setdefault("CLAUDE_CODE_MAX_CONTEXT_TOKENS", CLAUDE_CONTEXT_TOKENS)
        if "--bare" in args:
            env.pop("ANTHROPIC_AUTH_TOKEN", None)
            env["ANTHROPIC_API_KEY"] = key
        command = [executable, "--model", "yugos", "--strict-mcp-config"]
        if not any(a == "--settings" or a.startswith("--settings=") for a in args):
            # A caller's own --settings takes precedence; add the mapping to it.
            overrides = dict.fromkeys(CLAUDE_CLASSIFIER_MODELS, "yugos")
            command += ["--settings", json.dumps({"modelOverrides": overrides})]
    return command + list(args), env


def check_connection(env, cwd, env_file=None, environment=None):
    key, source = read_key(env, cwd, env_file)
    origin = api_origin(env, environment)
    try:
        data = fetch_json(origin, "/v1/models", key)
    except urllib.error.HTTPError as error:
        status = error.code
        error.close()
        raise ValueError(f"Yugos connection check returned HTTP {status}; check your key and API origin") from None
    except (urllib.error.URLError, TimeoutError, ValueError):
        raise ValueError("Yugos connection check failed; check your network and API origin") from None
    models = {item.get("id") for item in data.get("data", [])}
    if "yugos" not in models:
        raise ValueError("The model catalog does not advertise yugos for this key")
    print(f"Connected to {origin}; yugos is available. Key source: {source}.")
    print("No inference request was sent. Next, test an interactive reply and a file read/edit.")


def main(argv=None):
    if sys.version_info < (3, 11):
        raise SystemExit(
            f"yugos needs Python 3.11 or newer; {sys.executable} is {sys.version.split()[0]}. "
            "Rerun the installer to pick a newer Python."
        )
    argv = sys.argv if argv is None else argv
    args = argv[1:]
    # Help is ours only before a client; "yugos claude --help" reaches Claude Code.
    parser = argparse.ArgumentParser(
        prog="yugos", description=__doc__, allow_abbrev=False, add_help=False,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("command", choices=("claude", "codex", "pi", "opencode", "check"))
    parser.add_argument("--env", choices=tuple(ORIGINS), help="Yugos environment (default: YUGOS_ENV or production)")
    parser.add_argument("--env-file", help="Read the Yugos key from this file instead of automatic lookup")
    if not args or args[0] in ("-h", "--help", "help"):
        parser.print_help()
        return
    options, extra = parser.parse_known_args(args)
    try:
        if options.command == "check":
            check_connection(dict(os.environ), Path.cwd(), options.env_file, options.env)
            return
        command, env = build_command(
            options.command, extra, env_file=options.env_file, environment=options.env
        )
        os.execvpe(command[0], command, env)
    except (OSError, ValueError) as error:
        raise SystemExit(str(error)) from None


if __name__ == "__main__":
    main()
