"""Exercise the pinned Raxol Web3 MCP over stdio without wallet access."""
import argparse
import json
import os
from pathlib import Path
import re
import selectors
import subprocess
import sys

root = Path(__file__).resolve().parent
package = root / "raxol-agent/packages/raxol_payments"
state = root / ".start"
server_log = state / "mcp-server.log"
CHAINS = {"eip155:1": "Ethereum", "eip155:8453": "Base"}


class Stop(Exception):
    """A failure with the one line to print and the next action."""

    def __init__(self, message, action):
        super().__init__(message)
        self.action = action


class NoReply(Stop):
    """The server did not answer one request in time."""


def toolchain_env():
    """The toolchain and Mix home setup.sh resolved inside raxol-agent, so a python3
    shim's PATH cannot hand mix a different Elixir than the one the build used.
    Fails closed: one absolute entry per folder, mix, elixir and erl executable
    there, still Elixir 1.20.x on OTP 29. Returns (mix by absolute path, env)."""
    recorded = state / "toolchain"
    if not recorded.is_file() or not (package / "_build/dev").is_dir():
        raise Stop("no build found", "run sh setup.sh first")
    lines = [line.split("=", 1) for line in recorded.read_text().splitlines() if "=" in line]
    values = dict(lines)
    redo = "sh setup.sh toolchain, then rerun"
    for key in ("path", "elixir_bin", "erlang_bin"):
        if [k for k, _ in lines].count(key) != 1:
            raise Stop(f"the recorded toolchain has no single {key} entry", redo)
    elixir_bin, erlang_bin = Path(values["elixir_bin"]), Path(values["erlang_bin"])
    if values["path"] != f"{values['elixir_bin']}:{values['erlang_bin']}":
        raise Stop("the recorded toolchain path does not match its folders", redo)
    for folder in (elixir_bin, erlang_bin):
        if not folder.is_absolute() or not folder.is_dir():
            raise Stop(f"the recorded toolchain folder '{folder}' is missing or not absolute", redo)
    for tool in (elixir_bin / "mix", elixir_bin / "elixir", erlang_bin / "erl"):
        if not tool.is_file() or not os.access(tool, os.X_OK):
            raise Stop(f"the recorded toolchain has no executable {tool}", redo)
    inherited = [entry for entry in os.environ.get("PATH", "").split(os.pathsep) if entry not in ("", ".")]
    # web3-mcp.exs sets XDG itself; exporting it here would break mise shims.
    env = {**os.environ, "MIX_ENV": "dev",
           "PATH": os.pathsep.join([str(elixir_bin), str(erlang_bin), *inherited])}
    for name in ("MIX_HOME", "MIX_ARCHIVES"):
        env.pop(name, None)
        if values.get(name.lower()):
            env[name] = values[name.lower()]
    probe = 'IO.puts("#{System.version()} #{:erlang.system_info(:otp_release)}")'
    try:
        found = subprocess.run([str(elixir_bin / "elixir"), "--eval", probe], env=env, capture_output=True,
                               text=True, timeout=60, check=True).stdout.strip()
    except (subprocess.SubprocessError, OSError):
        raise Stop("the recorded toolchain no longer starts", redo) from None
    version, _, otp = found.partition(" ")
    if not version.startswith("1.20.") or otp != "29":
        raise Stop(f"the recorded toolchain is now Elixir/OTP '{found}'; need 1.20.x on OTP 29", redo)
    return str(elixir_bin / "mix"), env


def block_height(result):
    """Read the height from a web3_block_height result, whether the server returns
    JSON (structuredContent or text) or Elixir inspect text."""
    structured = result.get("structuredContent")
    texts = [item.get("text", "") for item in result.get("content", []) if isinstance(item, dict)]
    for text in texts:
        try:
            structured = structured or json.loads(text)
        except ValueError:
            pass
    if isinstance(structured, dict):
        for key in ("height", "total_blocks", "block_number", "latest_block"):
            if str(structured.get(key, "")).isdigit():
                return int(structured[key])
    match = re.search(r'"?\b(?:height|total_blocks|block_number|latest_block)"?\s*(?::|=>)\s*"?(\d+)',
                      " ".join(texts))
    return int(match.group(1)) if match else None


def source(result):
    """node or explorer. Blockscout, asked without an RPC URL, never reports a
    finalized height; a JSON-RPC node always does. (indexer is no signal: an
    explorer reports it as nil when its indexing status is unavailable.)"""
    text = json.dumps(result.get("structuredContent")) + " ".join(
        item.get("text", "") for item in result.get("content", []) if isinstance(item, dict))
    finalized = re.search(r'"?\bfinalized_height"?\s*(?::|=>)\s*"?(\d+)', text)
    return "node" if finalized else "explorer"


def error_fields(text):
    """The router error's code and detail, from either form the server sends:
    Elixir term text (%{code: "http", detail: 403}) or JSON ({"code":"http",...})."""
    start = text.find("{")
    if start != -1:
        try:
            error, _ = json.JSONDecoder().raw_decode(text[start:])
            if isinstance(error, dict) and "code" in error:
                return str(error["code"]), str(error.get("detail", ""))
        except ValueError:
            pass
    code = re.search(r'\bcode:\s*"(\w+)"', text)
    detail = re.search(r'\bdetail:\s*:?"?([\w.]+)', text)
    return (code.group(1) if code else ""), (detail.group(1) if detail else "")


def skip_reason(text):
    """Why a chain gave no height, from the router's error code, in the words the
    reads line prints. The last provider's error is the one reported."""
    code, detail = error_fields(text)
    if code == "http" and detail in ("401", "403", "429"):
        return "refused"
    if code == "breaker_open":
        return "paused"
    if code == "timeout" or (not code and re.search(r"time(?:d)? ?out", text, re.I)):
        return "timed out"
    if code in ("transport", "dns_failed"):
        return "unreachable"
    return "upstream error"


def run(outcome):
    mix, env = toolchain_env()
    state.mkdir(exist_ok=True)
    command = [mix, "run", "--no-start", "--no-compile", str(root / "web3-mcp.exs")]
    with open(server_log, "w") as errors, subprocess.Popen(
            command, cwd=package, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            stderr=errors, text=True, bufsize=1) as proc, selectors.DefaultSelector() as ready:
        ready.register(proc.stdout, selectors.EVENT_READ)

        def send(method, params, request_id=None):
            request = dict(jsonrpc="2.0", method=method, params=params)
            if request_id is not None:
                request["id"] = request_id
            try:
                proc.stdin.write(json.dumps(request) + "\n")
                proc.stdin.flush()
            except BrokenPipeError:
                raise Stop("the MCP server exited before answering",
                           f"see {server_log.relative_to(root)}, then rerun sh setup.sh") from None
            if request_id is None:
                return None
            # A reply to an earlier request that timed out may still arrive; skip it.
            while True:
                if not ready.select(45):
                    raise NoReply(f"no MCP response to {method} within 45s", "retry later")
                line = proc.stdout.readline()
                if not line:
                    raise Stop("the MCP server exited before answering",
                               f"see {server_log.relative_to(root)}, then rerun sh setup.sh")
                try:
                    reply = json.loads(line)
                except ValueError:
                    raise Stop("the MCP server wrote something other than JSON-RPC to stdout",
                               f"see {server_log.relative_to(root)}") from None
                if not (isinstance(reply.get("id"), int) and reply["id"] < request_id):
                    break
            if reply.get("id") != request_id or "error" in reply:
                raise Stop(f"MCP rejected {method}: {reply.get('error')}", "rerun sh setup.sh")
            return reply["result"]

        try:
            result = send("initialize", {
                "protocolVersion": "2025-03-26", "capabilities": {},
                "clientInfo": {"name": "axol-starter", "version": "1.0.0"}
            }, 1)
            print("MCP initialized:", result["serverInfo"]["name"])
            send("notifications/initialized", {})
            tools = [tool["name"] for tool in send("tools/list", {}, 2)["tools"]]
            if not tools or any(not name.startswith("web3_") for name in tools):
                raise Stop("the server exposed tools other than web3_*", "start again in an empty folder")
            print(f"Web3 tools ({len(tools)}):", ", ".join(tools))
            outcome["tools"] = tools
            # Each chain is its own outcome: a height is a read, anything else is skipped.
            outcome["reads"] = {}
            for request_id, (chain, name) in enumerate(CHAINS.items(), start=3):
                try:
                    result = send("tools/call", {"name": "web3_block_height", "arguments": {"chain": chain}},
                                  request_id)
                except NoReply:
                    result = {"isError": True, "content": [{"type": "text", "text": "timed out after 45s"}]}
                height = None if result.get("isError") else block_height(result)
                if height is None:
                    detail = " ".join(item.get("text", "") for item in result.get("content", [])
                                      if isinstance(item, dict))
                    reason = skip_reason(detail)
                    outcome["reads"][chain] = {"name": name, "status": "skipped", "reason": reason,
                                               "detail": detail[:300]}
                    print(f"{name} ({chain}): skipped ({reason}), not a read")
                else:
                    via = source(result)
                    outcome["reads"][chain] = {"name": name, "status": "read", "block": height, "source": via}
                    answered = "a public node (explorer unavailable)" if via == "node" else "the explorer"
                    print(f"{name} ({chain}): block {height} from {answered}")
            read = [r["name"] for r in outcome["reads"].values() if r["status"] == "read"]
            skipped = [f"{r['name']} ({r['reason']})" for r in outcome["reads"].values() if r["status"] != "read"]
            if not read:
                raise Stop(f"no chain was read: {', '.join(skipped)} skipped",
                           "retry later; never add credentials")
            if skipped:
                print(f"Read {', '.join(read)}; skipped {', '.join(skipped)}, not a read")
        finally:
            try:
                proc.stdin.close()
            except BrokenPipeError:
                pass  # the server already exited; that is reported above
            try:
                proc.wait(timeout=5)
            except subprocess.TimeoutExpired:
                proc.kill()


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--json", type=Path, help="also write the outcome to this JSON file")
    args = parser.parse_args()
    outcome = {}
    try:
        run(outcome)
    except Stop as stop:
        outcome["error"] = str(stop)
        print(f"check-mcp: {stop}", file=sys.stderr)
        print(f"fix:       {stop.action}", file=sys.stderr)
        sys.exit(1)
    finally:
        if args.json:
            args.json.write_text(json.dumps(outcome, indent=2) + "\n")
