#!/usr/bin/env python3
"""DeepWiki extension - MCP HTTP client for GitHub repo documentation"""

import json
import urllib.request
import ssl
import time

def mcp_call(tool_name, arguments):
    """Make MCP JSON-RPC call to DeepWiki"""
    url = "https://mcp.deepwiki.com/mcp"
    request_id = str(int(time.time() * 1000))

    data = {
        "jsonrpc": "2.0",
        "id": request_id,
        "method": "tools/call",
        "params": {
            "name": tool_name,
            "arguments": arguments
        }
    }

    try:
        # Create SSL context that doesn't verify certificates for mitmproxy
        ssl_context = ssl.create_default_context()
        ssl_context.check_hostname = False
        ssl_context.verify_mode = ssl.CERT_NONE
        
        req = urllib.request.Request(
            url,
            json.dumps(data).encode(),
            {
                "Content-Type": "application/json",
                "Accept": "application/json, text/event-stream"
            }
        )
        resp = urllib.request.urlopen(req, timeout=60, context=ssl_context)

        # Handle SSE response
        response_text = resp.read().decode()

        # Parse SSE format: extract JSON from "data: " lines
        for line in response_text.split('\n'):
            if line.startswith('data: '):
                data_str = line[6:].strip()  # Skip "data: " prefix

                # Skip ping events
                if data_str == "ping":
                    continue

                try:
                    result = json.loads(data_str)

                    if "error" in result:
                        return f"error: {result['error'].get('message', str(result['error']))}"

                    # Extract text from MCP response
                    content = result.get("result", {}).get("content", [])
                    if content:
                        texts = [item["text"] for item in content if item.get("type") == "text"]
                        if texts:
                            return "\n".join(texts)
                except json.JSONDecodeError:
                    continue

        return "error: No valid data in response"
    except Exception as e:
        return f"error: {type(e).__name__}: {e}"

@register_tool(
    "deepwiki_ask",
    "Ask questions about GitHub repo",
    {"repo": "string", "question": "string"}
)
def deepwiki_ask(args):
    """Ask a question about a GitHub repository (format: owner/repo)"""
    return mcp_call("ask_question", {
        "repoName": args["repo"],
        "question": args["question"]
    })

@register_tool(
    "deepwiki_structure",
    "Get repo documentation structure",
    {"repo": "string"}
)
def deepwiki_structure(args):
    """Get documentation structure/topics for a GitHub repository (format: owner/repo)"""
    return mcp_call("read_wiki_structure", {
        "repoName": args["repo"]
    })

@register_tool(
    "deepwiki_contents",
    "Get repo documentation contents",
    {"repo": "string"}
)
def deepwiki_contents(args):
    """Get full documentation contents for a GitHub repository (format: owner/repo)"""
    return mcp_call("read_wiki_contents", {
        "repoName": args["repo"]
    })
