#!/usr/bin/env python3
"""Code Claw Launcher - OpenRouter primary, Kimi fallback
Keys read at runtime from source files. No hardcoded secrets."""

import os, sys, json, subprocess, time

OR_KEY_FILE = r"/Users/apayne/.timmy/openrouter_key"
CLAW_BIN = r"/Users/apayne/code-claw/rust/target/debug/claw"
CONF_HOME = r"/Users/apayne/.claw-qwen36-openrouter"

# Models that support tool-use (bash). Ordered: try cheaper first.
MODELS = [
    "qwen/qwen3-235b-a22b",    # heavy hitter, tool-use capable
    "anthropic/claude-3.5-haiku-20241022",  # cheaper alternative
]

def probe(key, model, timeout=15):
    """Test if a model is available via OpenRouter."""
    try:
        r = subprocess.run(
            ["curl","-s","-o","/dev/null","-w","%{http_code}",
             "--max-time",str(timeout),
             "https://openrouter.ai/api/v1/chat/completions",
             "-H","Authorization: Bearer "+key,
             "-H","Content-Type: application/json",
             "-d",json.dumps({"model":model,"max_tokens":5,
                              "messages":[{"role":"user","content":"hi"}]})],
            capture_output=True, text=True, timeout=timeout+5)
        return int(r.stdout) if r.stdout.isdigit() else 0
    except Exception:
        return 0

def main():
    with open(OR_KEY_FILE) as f:
        key = f.read().strip()
    os.makedirs(CONF_HOME, exist_ok=True)
    os.chdir(os.path.dirname(CLAW_BIN))
    env = os.environ.copy()
    env["CLAW_FORCE_OPENAI_COMPAT"] = "1"
    env["OPENAI_API_KEY"] = key
    env["OPENAI_BASE_URL"] = "https://openrouter.ai/api/v1"
    env["CLAW_CONFIG_HOME"] = CONF_HOME
    print("Code Claw Launcher")
    print("=" * 50)
    for m in MODELS:
        s = probe(key, m)
        print("  Probe [%s]: HTTP %d" % (m, s))
        if s == 200:
            print("")
            print("  -> Launching with " + m)
            print("=" * 50)
            time.sleep(0.5)
            os.execve(CLAW_BIN, [CLAW_BIN, "--model", m], env)
            return
    print("")
    print("  -> OpenRouter unavailable. Falling back to Kimi CLI.")
    print("=" * 50)
    time.sleep(0.5)
    os.execvp("kimi-cli", ["kimi-cli"])

if __name__ == "__main__":
    main()
