#!/usr/bin/env python3
"""Demiurge connector — lets the build network use the AI on YOUR computer for YOUR builds.

Nothing listens on your machine: it only makes outgoing HTTPS requests to the studio, picks up model calls
for your builds, answers them with your AI, and sends the answer back. Your keys and models never leave it.

  python3 demiurge_connect.py --token dmc_...  --ai ollama  --model qwen3:14b
  python3 demiurge_connect.py --token dmc_...  --ai openai  --base http://localhost:1234/v1 --model local-model   (LM Studio, vLLM, llama.cpp)
  python3 demiurge_connect.py --token dmc_...  --ai cmd     --cmd "claude -p"          (Claude Code)
  python3 demiurge_connect.py --token dmc_...  --ai cmd     --cmd "codex exec -"       (Codex CLI)
  python3 demiurge_connect.py --token dmc_...  --ai cmd     --cmd "hermes chat -q -"   (Hermes; any CLI that reads stdin)

Standard library only. Stop with Ctrl+C."""
import argparse
import json
import shlex
import subprocess
import sys
import time
import urllib.error
import urllib.request

SITE = "https://demiurge-42a.pages.dev"


def http(method, url, body=None, headers=None, timeout=60):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, method=method,
                                 headers={"content-type": "application/json", "user-agent": "demiurge-connect/1", **(headers or {})})
    with urllib.request.urlopen(req, timeout=timeout) as r:
        raw = r.read()
        return r.status, (json.loads(raw) if raw else None)


def answer(args, prompt, system, max_tokens):
    if args.ai == "ollama":
        msgs = ([{"role": "system", "content": system}] if system else []) + [{"role": "user", "content": prompt}]
        _, d = http("POST", f"{args.base or 'http://localhost:11434'}/api/chat",
                    {"model": args.model, "messages": msgs, "stream": False, "options": {"num_predict": max_tokens}}, timeout=3600)
        return d["message"]["content"], {"prompt_tokens": d.get("prompt_eval_count", 0), "completion_tokens": d.get("eval_count", 0)}
    if args.ai == "openai":
        msgs = ([{"role": "system", "content": system}] if system else []) + [{"role": "user", "content": prompt}]
        h = {"Authorization": f"Bearer {args.key}"} if args.key else {}
        _, d = http("POST", f"{args.base.rstrip('/')}/chat/completions",
                    {"model": args.model, "messages": msgs, "max_tokens": max_tokens}, headers=h, timeout=3600)
        return d["choices"][0]["message"]["content"], d.get("usage") or {}
    if args.ai == "cmd":
        full = (f"{system}\n\n" if system else "") + prompt
        p = subprocess.run(shlex.split(args.cmd), input=full, capture_output=True, text=True, timeout=3600)
        if p.returncode != 0 and not p.stdout.strip():
            raise RuntimeError(f"{args.cmd} failed: {p.stderr.strip()[-300:]}")
        return p.stdout.strip(), {}
    raise SystemExit(f"unknown --ai {args.ai}")


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--token", required=True, help="connector token from your Demiurge studio page (dmc_...)")
    ap.add_argument("--ai", choices=["ollama", "openai", "cmd"], required=True)
    ap.add_argument("--model", default="")
    ap.add_argument("--base", default="", help="server URL for ollama/openai-compatible")
    ap.add_argument("--key", default="", help="API key for an openai-compatible server, if it needs one")
    ap.add_argument("--cmd", default="", help="CLI command that reads the prompt on stdin and prints the answer")
    ap.add_argument("--site", default=SITE)
    args = ap.parse_args()
    if args.ai == "openai" and not args.base:
        ap.error("--base is required for --ai openai")
    if args.ai == "cmd" and not args.cmd:
        ap.error("--cmd is required for --ai cmd")
    h = {"x-connector-token": args.token}
    print(f"Connected to {args.site} — waiting for model calls from your builds (Ctrl+C to stop)")
    wait = 3
    while True:
        try:
            st, d = http("GET", f"{args.site}/api/connector", headers=h, timeout=30)
            if st == 204 or not d:
                time.sleep(wait)
                wait = min(wait + 1, 10)
                continue
            wait = 3
            c = d["call"]
            print(f"call #{c['id']}: {len(c['prompt'])} chars …", end="", flush=True)
            t0 = time.time()
            try:
                text, usage = answer(args, c["prompt"], c.get("system") or "", int(c.get("max_tokens") or 8000))
            except Exception as e:
                text, usage = "", {"error": str(e)[:300]}
                print(f" error: {e}")
            http("POST", f"{args.site}/api/connector", {"id": c["id"], "text": text, "usage": usage}, headers=h, timeout=60)
            print(f" answered in {time.time() - t0:.0f}s ({len(text)} chars)")
        except urllib.error.HTTPError as e:
            if e.code == 401:
                sys.exit("The token was rejected — create a new one on your studio page.")
            print(f"server said {e.code}; retrying"); time.sleep(15)
        except (urllib.error.URLError, TimeoutError, ConnectionError) as e:
            print(f"network problem ({e}); retrying"); time.sleep(15)
        except KeyboardInterrupt:
            print("\nStopped."); return


if __name__ == "__main__":
    main()
