#!/usr/bin/env python3
"""Dependency-free stdio bridge for MarketRead Connect (Python 3.9+).

Set MARKETREAD_MCP_URL and MARKETREAD_AGENT_TOKEN in your MCP client's env.
Only JSON-RPC is written to stdout. Tokens are never accepted on the command line.
"""
import json
import os
import sys
from urllib.parse import urlparse
from urllib.request import Request, build_opener, HTTPRedirectHandler


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def main():
    url = os.environ.get("MARKETREAD_MCP_URL", "")
    token = os.environ.get("MARKETREAD_AGENT_TOKEN", "")
    parsed = urlparse(url)
    local = parsed.hostname in {"localhost", "127.0.0.1"}
    if (parsed.scheme != "https" and not (local and parsed.scheme == "http")) or parsed.path != "/api/connect/mcp" or parsed.username or parsed.password or parsed.query or not token.startswith("mrc_"):
        print("Configure a valid HTTPS MarketRead MCP endpoint and agent token in the environment.", file=sys.stderr)
        return 1
    opener = build_opener(NoRedirect())
    while True:
        line = sys.stdin.buffer.readline(32770)
        if not line:
            break
        if len(line) > 32768:
            print("MCP request too large.", file=sys.stderr)
            return 1
        request_id = None
        is_request = False
        try:
            message = json.loads(line)
            if not isinstance(message, dict):
                raise ValueError("Invalid request")
            request_id, is_request = message.get("id"), "id" in message
            req = Request(url, data=json.dumps(message).encode(), headers={"Content-Type": "application/json", "Accept": "application/json, text/event-stream", "Authorization": "Bearer " + token}, method="POST")
            with opener.open(req, timeout=60) as response:
                raw = response.read(2_000_001)
                if response.status == 202:
                    continue
            if len(raw) > 2_000_000:
                raise ValueError("Oversized response")
            payload = json.loads(raw)
            if is_request:
                print(json.dumps(payload, ensure_ascii=True), flush=True)
        except Exception:
            if is_request:
                print(json.dumps({"jsonrpc": "2.0", "id": request_id, "error": {"code": -32000, "message": "MarketRead connection failed. Check the endpoint, token, permissions and server status."}}), flush=True)
            else:
                print("MarketRead notification could not be delivered.", file=sys.stderr)
    return 0


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