#!/usr/bin/env python3
"""Minimal stdlib client for the public SiteDoctor Streamable HTTP MCP server."""

import argparse
import json
import os
import sys
import urllib.request
import urllib.error
from urllib.parse import urlparse

ENDPOINT = "https://manhourplan.com/doctor/mcp"
PROTOCOL = "2025-03-26"


def decode_response(response):
    raw = response.read().decode("utf-8")
    if not raw.strip():
        return None
    if raw.lstrip().startswith("{") or raw.lstrip().startswith("["):
        return json.loads(raw)
    events = []
    data_lines = []
    for line in raw.splitlines() + [""]:
        if line.startswith("data:"):
            data_lines.append(line[5:].strip())
        elif not line.strip() and data_lines:
            events.append(json.loads("\n".join(data_lines)))
            data_lines = []
    if not events:
        raise RuntimeError("The server returned no JSON-RPC result.")
    return events[-1]


class MCPClient:
    def __init__(self, endpoint=ENDPOINT, timeout=120):
        self.endpoint = endpoint
        self.timeout = timeout
        self.session = None
        self.next_id = 0

    def post(self, payload, notification=False):
        headers = {
            "Content-Type": "application/json",
            "Accept": "application/json, text/event-stream",
            "User-Agent": "sitedoctor-hermes-skill/1.0",
        }
        if self.session:
            headers["Mcp-Session-Id"] = self.session
        request = urllib.request.Request(
            self.endpoint,
            data=json.dumps(payload).encode("utf-8"),
            headers=headers,
            method="POST",
        )
        try:
            with urllib.request.urlopen(request, timeout=self.timeout) as response:
                if response.headers.get("Mcp-Session-Id"):
                    self.session = response.headers["Mcp-Session-Id"]
                return decode_response(response)
        except urllib.error.HTTPError as exc:
            detail = exc.read().decode("utf-8", "replace")[:500]
            raise RuntimeError(f"SiteDoctor HTTP {exc.code}: {detail}") from None
        except urllib.error.URLError as exc:
            raise RuntimeError(f"Cannot reach SiteDoctor: {exc.reason}") from None

    def call(self, tool, arguments):
        self.next_id += 1
        init_id = self.next_id
        result = self.post({
            "jsonrpc": "2.0",
            "id": init_id,
            "method": "initialize",
            "params": {
                "protocolVersion": PROTOCOL,
                "capabilities": {},
                "clientInfo": {"name": "sitedoctor-hermes-skill", "version": "1.0.0"},
            },
        })
        if not result or "error" in result:
            raise RuntimeError(f"Initialize failed: {result}")
        self.post({"jsonrpc": "2.0", "method": "notifications/initialized"}, notification=True)
        self.next_id += 1
        result = self.post({
            "jsonrpc": "2.0",
            "id": self.next_id,
            "method": "tools/call",
            "params": {"name": tool, "arguments": arguments},
        })
        if not result:
            raise RuntimeError("Empty tool response.")
        if "error" in result:
            raise RuntimeError(json.dumps(result["error"], ensure_ascii=False))
        return result.get("result", result)


def valid_url(value):
    parsed = urlparse(value)
    if parsed.scheme not in ("http", "https") or not parsed.netloc:
        raise argparse.ArgumentTypeError("Use a complete http:// or https:// URL.")
    return value


def key_from(args):
    key = getattr(args, "api_key", None) or os.environ.get("SITEDOCTOR_API_KEY", "")
    return key.strip()


def main():
    parser = argparse.ArgumentParser(description="Call SiteDoctor without installing dependencies.")
    sub = parser.add_subparsers(dest="command", required=True)
    sub.add_parser("register", help="Create a new API key with starter credits.")
    for name in ("scan", "seo", "links"):
        command = sub.add_parser(name)
        command.add_argument("url", type=valid_url)
        command.add_argument("--api-key", default="")
        if name == "links":
            command.add_argument("--max-links", type=int, default=25)
    credits = sub.add_parser("credits")
    credits.add_argument("--api-key", default="")
    args = parser.parse_args()

    if args.command == "register":
        tool, arguments = "register_free_key", {}
    elif args.command == "scan":
        tool, arguments = "scan_website", {"url": args.url, "api_key": key_from(args)}
    elif args.command == "seo":
        tool, arguments = "check_page_seo", {"url": args.url, "api_key": key_from(args)}
    elif args.command == "links":
        if not 1 <= args.max_links <= 50:
            parser.error("--max-links must be between 1 and 50")
        tool, arguments = "check_broken_links", {
            "url": args.url, "max_links": args.max_links, "api_key": key_from(args)
        }
    else:
        tool, arguments = "check_credits", {"api_key": key_from(args)}
        if not arguments["api_key"]:
            parser.error("credits requires --api-key or SITEDOCTOR_API_KEY")

    try:
        result = MCPClient().call(tool, arguments)
        print(json.dumps(result, ensure_ascii=False, indent=2))
    except (RuntimeError, json.JSONDecodeError) as exc:
        print(json.dumps({"error": str(exc)}, ensure_ascii=False), file=sys.stderr)
        return 1
    return 0


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