#!/usr/bin/env python3
"""Zero-dependency Model Context Protocol (MCP) stdio server for IndexSentinel Data APIs."""

from __future__ import annotations

import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from typing import Any

API_BASE = os.getenv("INDEXSENTINEL_API_BASE", "https://indexsentinelapp.com").rstrip("/")
API_KEY = os.getenv("INDEXSENTINEL_API_KEY", "").strip()

TOOLS: list[dict[str, Any]] = [
    {
        "name": "enrich_eu_company_vies",
        "description": (
            "Extract European company Impressum/legal data, VAT/P.IVA numbers, Italian PEC, "
            "commercial registry IDs, managing directors, Tech Stack, and live EU Commission VIES VAT validation."
        ),
        "inputSchema": {
            "type": "object",
            "properties": {
                "url": {"type": "string", "description": "Target EU company website or domain (e.g. https://www.hetzner.com)"},
                "verify_vies": {"type": "boolean", "default": True},
            },
            "required": ["url"],
        },
    },
    {
        "name": "search_apple_app_store",
        "description": "Search iOS App Store listings (ratings, bundle IDs, prices, developer websites).",
        "inputSchema": {
            "type": "object",
            "properties": {
                "q": {"type": "string"},
                "country": {"type": "string", "default": "us"},
                "limit": {"type": "integer", "default": 10},
            },
            "required": ["q"],
        },
    },
    {
        "name": "inspect_chrome_extension",
        "description": "Extract Chrome Web Store extension installs, rating, developer email/site & manifest permissions.",
        "inputSchema": {
            "type": "object",
            "properties": {"ext_id": {"type": "string"}},
            "required": ["ext_id"],
        },
    },
    {
        "name": "inspect_shopify_app",
        "description": "Extract Shopify App Store listing, pricing tiers, rating & developer metadata by handle.",
        "inputSchema": {
            "type": "object",
            "properties": {"handle": {"type": "string"}},
            "required": ["handle"],
        },
    },
    {
        "name": "fetch_substack_posts",
        "description": "Fetch recent or top posts from a Substack or custom newsletter via archive JSON + RSS fallback.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "url": {"type": "string"},
                "limit": {"type": "integer", "default": 10},
                "sort": {"type": "string", "enum": ["new", "top"], "default": "new"},
            },
            "required": ["url"],
        },
    },
]


def _call_api(path: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
    if not API_KEY:
        raise RuntimeError("INDEXSENTINEL_API_KEY is not set. Claim a free 7-day key at https://indexsentinelapp.com/apis#get-key")
    qs = urllib.parse.urlencode({k: v for k, v in (params or {}).items() if v is not None})
    url = f"{API_BASE}{path}" + (f"?{qs}" if qs else "")
    req = urllib.request.Request(
        url,
        headers={
            "X-IndexSentinel-API-Key": API_KEY,
            "Accept": "application/json",
            "User-Agent": "IndexSentinel-MCP/1.0",
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=25) as resp:
            return json.loads(resp.read().decode("utf-8"))
    except urllib.error.HTTPError as exc:
        body = exc.read().decode("utf-8", "replace")
        raise RuntimeError(f"HTTP {exc.code}: {body[:300]}") from exc


def _dispatch_tool(name: str, args: dict[str, Any]) -> dict[str, Any]:
    if name == "enrich_eu_company_vies":
        return _call_api("/api/v1/data/eu-impressum", {"url": args["url"], "verify_vies": str(args.get("verify_vies", True)).lower()})
    if name == "search_apple_app_store":
        return _call_api("/api/v1/data/apple-app-store/search", {"q": args["q"], "country": args.get("country", "us"), "limit": args.get("limit", 10)})
    if name == "inspect_chrome_extension":
        return _call_api(f"/api/v1/data/chrome-web-store/extension/{urllib.parse.quote(str(args['ext_id']))}")
    if name == "inspect_shopify_app":
        return _call_api(f"/api/v1/data/shopify-app/{urllib.parse.quote(str(args['handle']))}")
    if name == "fetch_substack_posts":
        return _call_api("/api/v1/data/substack/posts", {"url": args["url"], "limit": args.get("limit", 10), "sort": args.get("sort", "new")})
    raise ValueError(f"Unknown tool: {name}")


def _write_msg(payload: dict[str, Any]) -> None:
    sys.stdout.write(json.dumps(payload) + "\n")
    sys.stdout.flush()


def main() -> None:
    for line in sys.stdin:
        raw = line.strip()
        if not raw:
            continue
        req_id: Any = None
        try:
            msg = json.loads(raw)
            req_id = msg.get("id")
            method = msg.get("method", "")
            if method == "initialize":
                _write_msg({
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {
                        "protocolVersion": "2024-11-05",
                        "capabilities": {"tools": {}},
                        "serverInfo": {"name": "indexsentinel-data-mcp", "version": "1.0.0"},
                    },
                })
            elif method == "notifications/initialized":
                continue
            elif method == "tools/list":
                _write_msg({"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}})
            elif method == "tools/call":
                params = msg.get("params") or {}
                out = _dispatch_tool(str(params.get("name") or ""), dict(params.get("arguments") or {}))
                _write_msg({
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {"content": [{"type": "text", "text": json.dumps(out, indent=2)}]},
                })
            elif req_id is not None:
                _write_msg({"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {method}"}})
        except Exception as exc:
            if req_id is not None:
                _write_msg({
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "result": {"isError": True, "content": [{"type": "text", "text": str(exc)}]},
                })


if __name__ == "__main__":
    main()
