#!/usr/bin/env python3
# awesomate-muse-client
"""Call one Awesomate tool from Muse (or any shell) and print the answer.

Installed by the Awesomate connect as
~/workspace/custom-connectors/custom.awesomate/bin/client.py. Python 3,
standard library only. It starts the Awesomate MCP server over stdio, makes
one call and stops the server again. The server reads the key from
~/.awesomate/credentials.json itself: this helper never reads, prints or
passes a token.

    client.py call-tool <tool> ['<json arguments>']
    client.py list-tools
    client.py --account <slug> call-tool <tool> ['<json arguments>']

`call` and `tools` still work as the older names for `call-tool` and
`list-tools` (Muse's own helpers take call-tool and list-tools).

AWESOMATE_MCP_COMMAND (a JSON array) replaces the server command, for tests.
"""

import json
import os
import subprocess
import sys
import threading

SERVER = ["npx", "-y", "--package=@awesomate/hosting-mcp", "awesomate-hosting-mcp"]
TIMEOUT = float(os.environ.get("AWESOMATE_CLIENT_TIMEOUT", "300"))
PROTOCOL = "2025-06-18"

USAGE = (
    "Usage: client.py [--account <slug>] call-tool <tool> ['<json arguments>']\n"
    "       client.py [--account <slug>] list-tools\n"
    "(call and tools work too.)"
)

COMMANDS = {"call-tool": "call", "call": "call", "list-tools": "tools", "tools": "tools"}


def fail(message, code=1):
    sys.stderr.write(message.rstrip() + "\n")
    sys.exit(code)


class Server:
    def __init__(self, account):
        command = SERVER
        override = os.environ.get("AWESOMATE_MCP_COMMAND")
        if override:
            command = json.loads(override)
        elif os.name == "nt":
            command = ["cmd", "/c"] + SERVER
        env = dict(os.environ)
        if account:
            env["AWESOMATE_ACCOUNT"] = account
        try:
            self.proc = subprocess.Popen(
                command,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                env=env,
            )
        except FileNotFoundError:
            fail("Could not start the Awesomate MCP server: npx was not found. Install Node.js 18 or later.")
        self.stderr = []
        self.timed_out = False
        self.drainer = threading.Thread(target=self._drain, daemon=True)
        self.drainer.start()
        self.next_id = 0

    def kill(self):
        # On Windows the server runs under cmd /c, and killing cmd.exe leaves node holding the pipe.
        if os.name == "nt":
            subprocess.run(["taskkill", "/T", "/F", "/PID", str(self.proc.pid)],
                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        else:
            self.proc.kill()

    def expire(self):
        self.timed_out = True
        self.kill()

    def _drain(self):
        for line in self.proc.stderr:
            self.stderr.append(line.decode("utf-8", "replace"))

    def stopped(self):
        # The server's last words may still be on their way through the drain thread: let it exit
        # and finish reading them (briefly) before saying why it stopped.
        try:
            self.proc.wait(timeout=2)
        except Exception:
            pass
        self.drainer.join(timeout=2)
        tail = "".join(self.stderr[-5:]).strip()
        fail("The Awesomate MCP server stopped before it answered." + (("\n" + tail) if tail else ""))

    def send(self, message):
        try:
            self.proc.stdin.write((json.dumps(message) + "\n").encode("utf-8"))
            self.proc.stdin.flush()
        except (BrokenPipeError, OSError):
            # The server exited (npx offline, install failed): give its own words, never a traceback.
            try:
                self.proc.wait(timeout=2)
            except subprocess.TimeoutExpired:
                pass
            self.stopped()

    def request(self, method, params):
        self.next_id += 1
        wanted = self.next_id
        self.send({"jsonrpc": "2.0", "id": wanted, "method": method, "params": params})
        while True:
            line = self.proc.stdout.readline()
            if not line:
                if self.timed_out:
                    fail("No answer from the Awesomate MCP server within %d seconds." % TIMEOUT)
                self.stopped()
            try:
                message = json.loads(line)
            except ValueError:
                continue
            if "method" in message and "id" in message:
                # A request from the server. Answer a ping, refuse anything else.
                if message["method"] == "ping":
                    self.send({"jsonrpc": "2.0", "id": message["id"], "result": {}})
                else:
                    self.send({"jsonrpc": "2.0", "id": message["id"], "error": {"code": -32601, "message": "Not supported"}})
                continue
            if message.get("id") != wanted:
                continue
            if "error" in message:
                fail("The Awesomate MCP server refused the call: " + str(message["error"].get("message", message["error"])))
            return message.get("result", {})

    def start(self):
        self.request("initialize", {
            "protocolVersion": PROTOCOL,
            "capabilities": {},
            "clientInfo": {"name": "muse", "version": "1"},
        })
        self.send({"jsonrpc": "2.0", "method": "notifications/initialized"})

    def stop(self):
        try:
            self.proc.stdin.close()
        except OSError:
            pass
        try:
            self.proc.wait(timeout=5)
        except subprocess.TimeoutExpired:
            self.kill()


def text_of(result):
    parts = [c.get("text", "") for c in result.get("content", []) if c.get("type") == "text"]
    if parts:
        return "\n".join(parts)
    if "structuredContent" in result:
        return json.dumps(result["structuredContent"], indent=2)
    return json.dumps(result, indent=2)


def main(argv):
    account = None
    if len(argv) >= 2 and argv[0] == "--account":
        account = argv[1]
        argv = argv[2:]
    if not argv or argv[0] in ("-h", "--help"):
        fail(USAGE, 0 if argv else 2)
    command = COMMANDS.get(argv[0])
    if command == "call":
        if len(argv) < 2:
            fail(USAGE, 2)
        tool = argv[1]
        try:
            arguments = json.loads(argv[2]) if len(argv) > 2 and argv[2].strip() else {}
        except ValueError as err:
            fail("The arguments are not valid JSON: " + str(err), 2)
        if not isinstance(arguments, dict):
            fail("The arguments must be one JSON object, like '{\"domain\": \"example.com\"}'.", 2)
    elif command is None:
        fail(USAGE, 2)

    server = Server(account)
    timer = threading.Timer(TIMEOUT, server.expire)
    timer.daemon = True
    timer.start()
    try:
        server.start()
        if command == "tools":
            cursor = None
            while True:
                result = server.request("tools/list", {"cursor": cursor} if cursor else {})
                for t in result.get("tools", []):
                    first = (t.get("description") or "").strip().split("\n")[0]
                    print(t.get("name", "") + ": " + first[:160])
                cursor = result.get("nextCursor")
                if not cursor:
                    break
            return 0
        result = server.request("tools/call", {"name": tool, "arguments": arguments})
        out = text_of(result)
        if result.get("isError"):
            sys.stderr.write(out.rstrip() + "\n")
            return 1
        print(out)
        return 0
    finally:
        timer.cancel()
        server.stop()


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
