#!/usr/bin/env python3
"""Marketing Superman MCP STDIO bridge. Python 3; no third-party dependencies.
Set YXCR_API_TOKEN and optionally YXCR_MCP_URL before launching from an MCP client.
"""
import json
import os
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from urllib.request import Request, build_opener, HTTPRedirectHandler


class NoRedirect(HTTPRedirectHandler):
    # Never forward an account token to a redirected destination.
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def main():
    endpoint = os.environ.get('YXCR_MCP_URL', 'https://www.yingxiaochaoren.com/api/mcp')
    token = os.environ.get('YXCR_API_TOKEN', '')
    parsed = urlparse(endpoint)
    if not token or parsed.scheme not in ('https', 'http') or not parsed.hostname:
        print('Set YXCR_API_TOKEN and a valid YXCR_MCP_URL.', file=sys.stderr)
        return 1
    if parsed.scheme != 'https' and parsed.hostname not in ('localhost', '127.0.0.1', '::1') and not parsed.hostname.endswith('.local'):
        print('Remote MCP connections require HTTPS.', file=sys.stderr)
        return 1
    opener = build_opener(NoRedirect)
    protocol = None
    for line in sys.stdin:
        message = None
        try:
            message = json.loads(line)
            headers = {
                'Content-Type': 'application/json',
                'Accept': 'application/json, text/event-stream',
                'Authorization': 'Bearer ' + token,
            }
            if protocol:
                headers['MCP-Protocol-Version'] = protocol
            request = Request(endpoint, data=line.encode('utf-8'), method='POST', headers=headers)
            with opener.open(request, timeout=120) as response:
                body = response.read()
                if body:
                    reply = json.loads(body)
                    if isinstance(message, dict) and message.get('method') == 'initialize':
                        protocol = reply.get('result', {}).get('protocolVersion')
                    print(json.dumps(reply, ensure_ascii=False), flush=True)
        except (HTTPError, URLError, TimeoutError, OSError, ValueError) as exc:
            # No retries: a timed-out write may already have succeeded.
            if isinstance(message, dict) and 'id' in message:
                if isinstance(exc, HTTPError):
                    detail = 'MCP HTTP error ' + str(exc.code)
                else:
                    detail = 'MCP request failed; check connection and token. Verify write status before retrying.'
                print(json.dumps({'jsonrpc': '2.0', 'id': message['id'], 'error': {
                    'code': -32603, 'message': detail}}), flush=True)
            else:
                print('MCP notification could not be forwarded.', file=sys.stderr)
    return 0


if __name__ == '__main__':
    sys.exit(main())
