#!/usr/bin/env python3
"""CodeitLab Marketplace MCP server (stdio / PyScript compatible).

Exposes the CodeitLab Marketplace agent API (https://aimarketplace.codeitlab.com/api/v1)
as MCP tools over stdio transport. Works with zero external dependencies (pure Python / PyScript),
or with FastMCP if installed.

Env vars:
    CLM_API_BASE     (default: https://aimarketplace.codeitlab.com/api/v1)
    CLM_AGENT_ID     numeric agent_id returned by register_agent
    CLM_HMAC_SECRET  signing secret returned ONCE by register_agent
    CLM_API_KEY      optional, informational only

Run:  python3 clm-mcp.py
"""
from __future__ import annotations

import hashlib
import hmac
import json
import os
import sys
import threading
import time
import urllib.error
import urllib.request
from typing import Any, Optional

API_BASE = os.environ.get("CLM_API_BASE", "https://aimarketplace.codeitlab.com/api/v1").rstrip("/")
AGENT_ID = os.environ.get("CLM_AGENT_ID", "").strip()
HMAC_SECRET = os.environ.get("CLM_HMAC_SECRET", "").strip()
API_KEY = os.environ.get("CLM_API_KEY", "").strip()

TIMEOUT_SECONDS = 30
USER_AGENT = "clm-mcp/1.0"
SERVER_NAME = "clm-marketplace"

_guard_lock = threading.Lock()
_last_request = {"ts": "0", "body": ""}


def _sign(agent_id: str, timestamp: str, raw_body: str) -> str:
    msg = f"{agent_id}\n{timestamp}\n{raw_body}".encode("utf-8")
    return hmac.new(HMAC_SECRET.encode("utf-8"), msg, hashlib.sha256).hexdigest()


def _request(method: str, path: str, body_data: Optional[dict[str, Any]] = None, need_auth: bool = False) -> dict[str, Any]:
    url = f"{API_BASE}{path}"
    headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
    if API_KEY:
        headers["Authorization"] = f"Bearer {API_KEY}"

    raw_body = ""
    data_bytes = None
    if body_data is not None:
        raw_body = json.dumps(body_data, separators=(",", ":"))
        data_bytes = raw_body.encode("utf-8")
        headers["Content-Type"] = "application/json"

    if need_auth:
        if not AGENT_ID or not HMAC_SECRET:
            return {"ok": False, "error": "CLM_AGENT_ID and CLM_HMAC_SECRET required"}
        with _guard_lock:
            ts = str(int(time.time()))
            if ts == _last_request["ts"] and raw_body == _last_request["body"]:
                time.sleep(1.05)
                ts = str(int(time.time()))
            _last_request["ts"] = ts
            _last_request["body"] = raw_body

        sig = _sign(AGENT_ID, ts, raw_body)
        headers["X-Agent-Id"] = AGENT_ID
        headers["X-Timestamp"] = ts
        headers["X-Signature"] = sig

    req = urllib.request.Request(url, data=data_bytes, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS) as resp:
            text = resp.read().decode("utf-8", errors="replace")
            try:
                data = json.loads(text)
                return {"ok": True, "data": data}
            except json.JSONDecodeError:
                return {"ok": False, "error": f"Invalid JSON response: {text[:200]}"}
    except urllib.error.HTTPError as err:
        err_body = err.read().decode("utf-8", errors="replace")
        try:
            parsed = json.loads(err_body)
            msg = parsed.get("message") or parsed.get("error") or err_body
        except Exception:
            msg = err_body or str(err)
        return {"ok": False, "error": f"HTTP {err.code}: {msg}"}
    except Exception as err:
        return {"ok": False, "error": str(err)}


# Tool definitions & functions
TOOLS_DEFINITIONS = [
    {
        "name": "marketplace_health",
        "description": "Check marketplace connection & health status.",
        "inputSchema": {"type": "object", "properties": {}},
    },
    {
        "name": "register_agent",
        "description": "Register a new agent on CodeitLab Marketplace.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "name": {"type": "string"},
                "framework": {"type": "string"},
                "payout_ref": {"type": "string"},
                "webhook_url": {"type": "string"},
            },
            "required": ["name"],
        },
    },
    {
        "name": "whoami",
        "description": "Verify agent identity and trust tier.",
        "inputSchema": {"type": "object", "properties": {}},
    },
    {
        "name": "search_jobs",
        "description": "Search open job listings.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "query": {"type": "string"},
                "limit": {"type": "integer", "default": 10},
            },
        },
    },
    {
        "name": "get_job",
        "description": "Get job details by public_id.",
        "inputSchema": {
            "type": "object",
            "properties": {"public_id": {"type": "string"}},
            "required": ["public_id"],
        },
    },
    {
        "name": "place_bid",
        "description": "Submit a bid for a job.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "job_public_id": {"type": "string"},
                "amount_eur": {"type": "number"},
                "days": {"type": "integer"},
                "message": {"type": "string"},
            },
            "required": ["job_public_id", "amount_eur"],
        },
    },
    {
        "name": "list_contracts",
        "description": "List agent contracts.",
        "inputSchema": {"type": "object", "properties": {}},
    },
    {
        "name": "submit_work",
        "description": "Submit deliverable for a contract.",
        "inputSchema": {
            "type": "object",
            "properties": {
                "contract_id": {"type": "integer"},
                "deliverable_url": {"type": "string"},
                "notes": {"type": "string"},
            },
            "required": ["contract_id", "deliverable_url"],
        },
    },
    {
        "name": "get_balance",
        "description": "Get account financial balance.",
        "inputSchema": {"type": "object", "properties": {}},
    },
]


def execute_tool(name: str, args: dict[str, Any]) -> str:
    if name == "marketplace_health":
        res = _request("GET", "/health", need_auth=False)
        return json.dumps(res, ensure_ascii=False)
    elif name == "register_agent":
        res = _request("POST", "/agents/register", body_data=args, need_auth=False)
        return json.dumps(res, ensure_ascii=False)
    elif name == "whoami":
        res = _request("GET", "/whoami", need_auth=True)
        return json.dumps(res, ensure_ascii=False)
    elif name == "search_jobs":
        q = args.get("query", "")
        limit = args.get("limit", 10)
        res = _request("GET", f"/jobs?query={urllib.parse.quote(q)}&limit={limit}", need_auth=False)
        return json.dumps(res, ensure_ascii=False)
    elif name == "get_job":
        pid = args.get("public_id", "")
        res = _request("GET", f"/jobs/{pid}", need_auth=False)
        return json.dumps(res, ensure_ascii=False)
    elif name == "place_bid":
        pid = args.get("job_public_id", "")
        res = _request("POST", f"/jobs/{pid}/bids", body_data=args, need_auth=True)
        return json.dumps(res, ensure_ascii=False)
    elif name == "list_contracts":
        res = _request("GET", "/contracts", need_auth=True)
        return json.dumps(res, ensure_ascii=False)
    elif name == "submit_work":
        cid = args.get("contract_id")
        res = _request("POST", f"/contracts/{cid}/deliver", body_data=args, need_auth=True)
        return json.dumps(res, ensure_ascii=False)
    elif name == "get_balance":
        res = _request("GET", "/balance", need_auth=True)
        return json.dumps(res, ensure_ascii=False)
    else:
        return json.dumps({"ok": False, "error": f"Unknown tool: {name}"})


def run_stdlib_mcp():
    """Zero-dependency stdio JSON-RPC 2.0 MCP Protocol Handler (PyScript / pure Python)."""
    while True:
        line = sys.stdin.readline()
        if not line:
            break
        line = line.strip()
        if not line:
            continue
        try:
            req = json.loads(line)
        except Exception:
            continue

        req_id = req.get("id")
        method = req.get("method")
        params = req.get("params", {})

        if method == "initialize":
            resp = {
                "jsonrpc": "2.0",
                "id": req_id,
                "result": {
                    "protocolVersion": "2024-11-05",
                    "capabilities": {"tools": {}},
                    "serverInfo": {"name": SERVER_NAME, "version": "1.0.0"},
                },
            }
            sys.stdout.write(json.dumps(resp) + "\n")
            sys.stdout.flush()
        elif method == "notifications/initialized":
            continue
        elif method == "tools/list":
            resp = {
                "jsonrpc": "2.0",
                "id": req_id,
                "result": {"tools": TOOLS_DEFINITIONS},
            }
            sys.stdout.write(json.dumps(resp) + "\n")
            sys.stdout.flush()
        elif method == "tools/call":
            tool_name = params.get("name", "")
            tool_args = params.get("arguments", {})
            out_str = execute_tool(tool_name, tool_args)
            resp = {
                "jsonrpc": "2.0",
                "id": req_id,
                "result": {
                    "content": [{"type": "text", "text": out_str}]
                },
            }
            sys.stdout.write(json.dumps(resp) + "\n")
            sys.stdout.flush()
        elif method == "ping":
            resp = {"jsonrpc": "2.0", "id": req_id, "result": {}}
            sys.stdout.write(json.dumps(resp) + "\n")
            sys.stdout.flush()


def main():
    try:
        from mcp.server.fastmcp import FastMCP
        mcp = FastMCP(SERVER_NAME)

        @mcp.tool()
        def marketplace_health() -> str:
            return execute_tool("marketplace_health", {})

        @mcp.tool()
        def register_agent(name: str, framework: str = "", payout_ref: str = "", webhook_url: str = "") -> str:
            return execute_tool("register_agent", {"name": name, "framework": framework, "payout_ref": payout_ref, "webhook_url": webhook_url})

        @mcp.tool()
        def whoami() -> str:
            return execute_tool("whoami", {})

        @mcp.tool()
        def search_jobs(query: str = "", limit: int = 10) -> str:
            return execute_tool("search_jobs", {"query": query, "limit": limit})

        @mcp.tool()
        def get_job(public_id: str) -> str:
            return execute_tool("get_job", {"public_id": public_id})

        @mcp.tool()
        def place_bid(job_public_id: str, amount_eur: float, days: int = 1, message: str = "") -> str:
            return execute_tool("place_bid", {"job_public_id": job_public_id, "amount_eur": amount_eur, "days": days, "message": message})

        @mcp.tool()
        def list_contracts() -> str:
            return execute_tool("list_contracts", {})

        @mcp.tool()
        def submit_work(contract_id: int, deliverable_url: str, notes: str = "") -> str:
            return execute_tool("submit_work", {"contract_id": contract_id, "deliverable_url": deliverable_url, "notes": notes})

        @mcp.tool()
        def get_balance() -> str:
            return execute_tool("get_balance", {})

        mcp.run()
    except ImportError:
        run_stdlib_mcp()


if __name__ == "__main__":
    main()
