#!/usr/bin/env python3
"""Register solwebd as a ccr provider, idempotently.

ccr's config is hand-maintained and holds live keys for every other provider, so this
upserts only the `solweb` entry and rewrites nothing else. Run it after a ccr config
reset — without the entry, `sw` dispatches get a 404 that reads like a bad model.
"""

from __future__ import annotations

import json
import os
import pathlib
import sys

CONFIG = pathlib.Path(os.environ.get("CCR_CONFIG_FILE",
                                     pathlib.Path.home() / ".claude-code-router" / "config.json"))
TOKEN_FILE = pathlib.Path(os.environ.get("SOLWEBD_TOKEN_FILE",
                                         pathlib.Path.home() / ".overdeck" / "gptbridge" / "solwebd.token"))
PORT = os.environ.get("SOLWEBD_PORT", "8791")
MODELS = ["sol-web-instant", "sol-web-medium", "sol-web-high", "sol-web-xhigh", "sol-web-pro"]


def main() -> int:
    if not TOKEN_FILE.is_file():
        print(f"no solwebd token at {TOKEN_FILE} — start solwebd once first", file=sys.stderr)
        return 3
    if not CONFIG.is_file():
        print(f"no ccr config at {CONFIG} — install ccr first", file=sys.stderr)
        return 3
    config = json.loads(CONFIG.read_text())
    entry = {"name": "solweb",
             "api_base_url": f"http://127.0.0.1:{PORT}/v1/chat/completions",
             "api_key": TOKEN_FILE.read_text().strip(),
             "models": MODELS}
    providers = config.setdefault("Providers", [])
    for index, provider in enumerate(providers):
        if provider.get("name") == "solweb":
            if provider == entry:
                print("solweb provider already current")
                return 0
            providers[index] = entry
            break
    else:
        providers.append(entry)
    CONFIG.write_text(json.dumps(config, indent=2) + "\n")
    print("solweb provider written — restart ccr to pick it up (`ccr restart`)")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
