#!/usr/bin/env bash
# Elysium AI IDE setup 2026.11.02 (codex)
# Download this file, then run it from a terminal:
#   bash codex.sh
#   bash codex.sh --model <public-model-id>
# Other options: --dry-run, --status, --uninstall, --key-stdin.
# The API key is never an argument.
set -euo pipefail
umask 077
command -v python3 >/dev/null 2>&1 || { printf '%s\n' 'Python 3.9+ is required. Install it, then rerun this script.' >&2; exit 1; }
setup_tmp="$(mktemp -d "${TMPDIR:-/tmp}/elysium-setup.XXXXXXXX")"
trap 'rm -rf -- "$setup_tmp"' EXIT
cat > "$setup_tmp/ide.py" <<'ELYSIUM_PYTHON'
#!/usr/bin/env python3
"""Elysium AI IDE configuration installer, version 2026.11.02."""
import argparse
import csv
import getpass
import json
import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
import warnings

VERSION = "2026.11.02"
HOST = "https://elysiumai.net"
TOOLS = ("codex", "claude-code")
BEGIN = "# >>> elysium-ai >>>"
END = "# <<< elysium-ai <<<"
JOIN = "# elysium-ai: original file had no final newline"


class Parser(argparse.ArgumentParser):
    def error(self, message):
        # argparse quotes rejected values; a key mistakenly typed as an argument must not be echoed.
        redacted = re.sub(r"sk-[A-Za-z0-9._-]*", "[hidden]", message)
        if redacted != message:
            redacted += " (API keys are never accepted as arguments: use the hidden prompt, ELYSIUM_API_KEY or --key-stdin)"
        super().error(redacted)


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


def fail(message):
    raise ValueError(message)


def safe_path(path):
    for parent in (path, *path.parents):
        if parent.is_symlink():
            fail("Refusing a symbolic-link configuration path.")
    if path.exists() and not path.is_file():
        fail("Expected a regular configuration file.")


def read(path):
    safe_path(path)
    return path.read_text(encoding="utf-8-sig") if path.exists() else ""


def strip_block(text):
    if text.count(BEGIN) != text.count(END) or text.count(BEGIN) > 1:
        fail("Invalid Elysium AI markers; restore the file from backup first.")
    if BEGIN not in text:
        return text
    start = text.index(BEGIN)
    stop = text.index(END)
    if stop < start or (start and text[start - 1] != "\n"):
        fail("Invalid Elysium AI markers.")
    joined = text[start:].startswith(BEGIN + "\n" + JOIN + "\n")
    stop += len(END)
    if text[stop:stop + 1] == "\n":
        stop += 1
    if joined and start and text[stop:] == "":
        start -= 1
    return text[:start] + text[stop:]


def block(content):
    return BEGIN + "\n" + content.rstrip() + "\n" + END + "\n"


def replace_block(text, content):
    if BEGIN in text:
        strip_block(text)
        if BEGIN + "\n" + JOIN + "\n" in text:
            content = JOIN + "\n" + content
        return re.sub(re.escape(BEGIN) + r".*?" + re.escape(END) + r"\n?", lambda _: block(content), text, flags=re.S)
    if text and not text.endswith("\n"):
        return text + "\n" + block(JOIN + "\n" + content)
    return text + block(content)


def atomic_write(path, data):
    safe_path(path)
    path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    fd, tmp = tempfile.mkstemp(prefix=".elysium-", dir=str(path.parent))
    try:
        if os.name == "nt":
            system = Path(os.environ.get("SystemRoot", "C:\\Windows")) / "System32"
            identity = subprocess.run([str(system / "whoami.exe"), "/user", "/fo", "csv", "/nh"], capture_output=True, text=True)
            entries = list(csv.reader(identity.stdout.splitlines()))
            sid = entries[0][-1].strip() if identity.returncode == 0 and entries else ""
            if not re.fullmatch(r"S-1-(?:\d+-)*\d+", sid):
                os.close(fd)
                fail("Could not determine the current Windows user SID.")
            result = subprocess.run([str(system / "icacls.exe"), tmp, "/inheritance:r", "/grant:r", "*" + sid + ":F"], capture_output=True)
            if result.returncode:
                os.close(fd)
                fail("Could not protect the configuration file with a private Windows ACL.")
        with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as target:
            target.write(data)
            target.flush()
            os.fsync(target.fileno())
        os.replace(tmp, path)
    finally:
        if os.path.exists(tmp):
            os.unlink(tmp)


def validate_key(key, model):
    if not re.fullmatch(r"sk-[A-Za-z0-9._-]{12,240}", key):
        fail("Expected an sk- API key. Pass it using the hidden prompt or --key-stdin.")
    request = urllib.request.Request(HOST + "/v1/models", headers={"Authorization": "Bearer " + key})
    try:
        with urllib.request.build_opener(NoRedirect).open(request, timeout=20) as response:
            payload = json.loads(response.read(4 * 1024 * 1024))
        if model not in [row.get("id") for row in payload.get("data", [])]:
            fail("Selected model is not available to this key. Choose a public model from the catalog.")
    except (urllib.error.URLError, json.JSONDecodeError, KeyError):
        fail("API key/model verification failed. Check your key, model and network; no files were changed.")


def codex_config(model):
    return ('model = ' + json.dumps(model) + '\nmodel_provider = "elysium"\n\n'
            '[model_providers.elysium]\nname = "Elysium AI"\n'
            'base_url = "' + HOST + '/v1"\nwire_api = "responses"\n'
            'env_key = "ELYSIUM_API_KEY"\n')


def main():
    parser = Parser(description="Configure installed Codex or Claude Code. No client downloads, shell-profile edits or telemetry.")
    parser.add_argument("--tool", required=True, choices=[*TOOLS, "claude"])
    parser.add_argument("--model")
    actions = parser.add_mutually_exclusive_group()
    actions.add_argument("--dry-run", action="store_true")
    actions.add_argument("--status", action="store_true")
    actions.add_argument("--uninstall", action="store_true")
    parser.add_argument("--key-stdin", action="store_true", help="Read the API key from standard input, never from arguments")
    parser.add_argument("--version", action="version", version=VERSION)
    args = parser.parse_args()
    if args.tool == "claude":
        args.tool = "claude-code"
    model = args.model or ("openai/gpt-6-luna" if args.tool == "codex" else "anthropic/claude-sonnet-5")
    if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,199}", model):
        fail("Invalid public model ID.")
    os.umask(0o077)
    home = Path.home()
    root = home / ".elysium-setup"
    codex = Path(os.environ.get("CODEX_HOME", str(home / ".codex"))).absolute()
    claude = Path(os.environ.get("CLAUDE_CONFIG_DIR", str(home / ".claude"))).absolute()
    config = codex / "elysium.config.toml" if args.tool == "codex" else claude / "settings.json"
    state_path = root / "state" / (args.tool + ".json")
    for path in (config, state_path):
        safe_path(path)
    if args.status:
        present = BEGIN in read(config) if args.tool == "codex" else bool(read(state_path))
        print(args.tool + ": " + ("configured" if present else "not configured"))
        return
    if args.dry_run:
        print("Dry run: no network requests, no key read, no files written.")
        print("Tool: " + args.tool + "; model: " + model)
        print("Update: " + str(config))
        if args.tool == "codex":
            print("Update managed .env blocks: " + str(codex / ".env") + ", " + str(codex / "elysium-desktop" / ".env"))
            print("Update isolated Desktop config: " + str(codex / "elysium-desktop" / "config.toml"))
            print(block(codex_config(model)))
        else:
            print("Merge only managed env keys; preserve their original values for uninstall. Key: [hidden]")
        return
    root.mkdir(parents=True, exist_ok=True, mode=0o700)
    lock = root / ".lock"
    try:
        lock.mkdir(mode=0o700)
    except FileExistsError:
        fail("Another installer is running. If it exited unexpectedly, remove ~/.elysium-setup/.lock first.")
    try:
        run(args, model, codex, claude, config, state_path, root)
    finally:
        lock.rmdir()


def run(args, model, codex, claude, config, state_path, root):
    changes = {}
    original = read(config)
    state_text = read(state_path)
    state = json.loads(state_text) if state_text else None
    if state and state.get("config") != str(config):
        fail("This tool is managed at another configuration path. Uninstall there first.")
    if args.uninstall:
        if args.tool == "codex":
            for path in (config, codex / ".env", codex / "elysium-desktop" / "config.toml", codex / "elysium-desktop" / ".env"):
                text = read(path)
                if BEGIN in text:
                    changes[path] = strip_block(text) or None
        elif state:
            data = json.loads(original) if original.strip() else {}
            env = data.get("env", {})
            for key, installed in state["installed"].items():
                if env.get(key) == installed:
                    if key in state["previous"]:
                        env[key] = state["previous"][key]
                    else:
                        env.pop(key, None)
            if not env and not state.get("had_env"):
                data.pop("env", None)
            if original.strip():
                changes[config] = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
        if state:
            changes[state_path] = None
    else:
        key = os.environ.get("ELYSIUM_API_KEY", "")
        if args.key_stdin:
            key = sys.stdin.readline().strip()
            if not key:
                fail("--key-stdin received no key. A piped installer (curl ... | bash) cannot also read the key from standard input; use the hidden prompt or ELYSIUM_API_KEY.")
        elif not key:
            # getpass opens the controlling terminal (/dev/tty) itself, so a script piped into bash
            # still gets a hidden prompt; without a terminal the warning below stops it before any
            # visible fallback read from standard input.
            with warnings.catch_warnings():
                warnings.simplefilter("error", getpass.GetPassWarning)
                try:
                    key = getpass.getpass("Elysium AI API key (hidden): ")
                except getpass.GetPassWarning:
                    fail("The hidden API key prompt needs an interactive terminal. Run this command in a terminal, set ELYSIUM_API_KEY for this process, or download the script and pass the key with --key-stdin (-KeyStdin in PowerShell).")
        validate_key(key, model)
        if args.tool == "codex":
            for path, content in ((config, codex_config(model)),
                                  (codex / ".env", "ELYSIUM_API_KEY=" + key),
                                  (codex / "elysium-desktop" / "config.toml", codex_config(model)),
                                  (codex / "elysium-desktop" / ".env", "ELYSIUM_API_KEY=" + key)):
                current = read(path)
                outside = strip_block(current)
                if path.suffix == ".toml" and outside.strip():
                    fail("An unmanaged Elysium profile file exists. Move it aside before installing.")
                if path.name == ".env" and re.search(r"(?m)^\s*(?:export\s+)?ELYSIUM_API_KEY\s*=", outside):
                    fail("An unmanaged ELYSIUM_API_KEY exists in .env. Move it aside before installing.")
                changes[path] = replace_block(current, content)
        else:
            data = json.loads(original) if original.strip() else {}
            if not original.strip():
                state = None
            if not isinstance(data, dict) or not isinstance(data.get("env", {}), dict):
                fail("Claude settings and env must be JSON objects.")
            if "apiKeyHelper" in data:
                fail("Claude apiKeyHelper is configured. Configure a separate CLAUDE_CONFIG_DIR instead.")
            env = data.setdefault("env", {})
            managed = {"ANTHROPIC_BASE_URL": HOST, "ANTHROPIC_AUTH_TOKEN": key,
                       "ANTHROPIC_API_KEY": "", "ANTHROPIC_MODEL": model,
                       "ANTHROPIC_DEFAULT_SONNET_MODEL": model,
                       "ANTHROPIC_DEFAULT_OPUS_MODEL": model,
                       "ANTHROPIC_DEFAULT_HAIKU_MODEL": model}
            previous = state["previous"] if state else {k: env[k] for k in managed if k in env}
            for k in managed:
                if state and env.get(k) != state["installed"].get(k):
                    fail("Managed Claude settings changed since installation. Uninstall before reinstalling.")
            state = {"config": str(config), "previous": previous, "installed": managed,
                     "had_env": state["had_env"] if state else "env" in (json.loads(original) if original.strip() else {})}
            env.update(managed)
            changes[config] = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
            changes[state_path] = json.dumps(state, indent=2) + "\n"
    changes = {p: v for p, v in changes.items() if (p.exists() if v is None else read(p) != v)}
    if not changes:
        print("No changes needed.")
        return
    backup = root / "backups" / (args.tool + "-" + str(time.time_ns()))
    backup.mkdir(parents=True, mode=0o700)
    snapshots = {}
    for index, path in enumerate(changes):
        safe_path(path)
        snapshots[path] = (path.read_bytes(), stat.S_IMODE(path.stat().st_mode)) if path.exists() else None
        if path.exists():
            atomic_write(backup / str(index), path.read_text(encoding="utf-8-sig"))
    atomic_write(backup / "paths.json", json.dumps([str(p) for p in changes], indent=2))
    try:
        for path, value in changes.items():
            if value is None:
                path.unlink()
            else:
                atomic_write(path, value)
    except Exception:
        for path, snapshot in snapshots.items():
            if snapshot is None:
                if path.exists():
                    path.unlink()
            else:
                atomic_write(path, snapshot[0].decode("utf-8-sig"))
                os.chmod(path, snapshot[1])
        raise
    backups = sorted((root / "backups").glob(args.tool + "-*"), key=lambda p: p.name, reverse=True)
    for old in backups[5:]:
        if not old.is_symlink():
            shutil.rmtree(old)
    print(("Removed managed settings." if args.uninstall else "Configured " + args.tool + ".") + " Backup: " + str(backup))
    if not args.uninstall and args.tool == "codex":
        print("Codex CLI 0.166+: codex -p elysium")
        print("Desktop: launch with CODEX_HOME=" + str(codex / "elysium-desktop") + " using codex app. Restart and create a new task.")
    elif not args.uninstall:
        print("Restart Claude Code. Configured model aliases all use your selected model.")


if __name__ == "__main__":
    try:
        main()
    except (ValueError, OSError, json.JSONDecodeError) as error:
        # Do not render exception text: parsers/network libraries may include credentials.
        message = str(error) if type(error) is ValueError else "Configuration failed. Check file permissions and JSON syntax; no credentials are shown."
        print("Error: " + message, file=sys.stderr)
        sys.exit(1)
ELYSIUM_PYTHON
script_on_stdin=0
case "$-" in *c*) ;; *) [ -n "${BASH_SOURCE[0]:-}" ] || script_on_stdin=1 ;; esac
if [ "$script_on_stdin" = 1 ]; then
  python3 "$setup_tmp/ide.py" --tool codex "$@" </dev/null
else
  python3 "$setup_tmp/ide.py" --tool codex "$@"
fi
