from __future__ import annotations

import json
import time
from typing import Annotated

from mcp.server.fastmcp import FastMCP

from ..api_client import api_post_json
from ..auth import resolve_auth
from ..security.audit import audit_log, sanitize_args
from ..security.metrics import record_auth_failure, record_throttle_rejection, record_tool_call
from ..security.throttle import check_throttle

TOOL = "list_on_marketplace"


def register(mcp: FastMCP) -> None:
    @mcp.tool(
        name="list_on_marketplace",
        description=(
            "List an already-uploaded file on the public AgentVee marketplace. "
            "The upload must be READY status and have a price set. "
            "Returns the marketplace URL where buyers can find and download the file. "
            "Requires the agent key owner to own the upload."
        ),
    )
    async def list_on_marketplace(
        uploadId: Annotated[str, "Upload ID to list (e.g. up_a1b2c3d4e5f6g7h8)"],
        title: Annotated[str, "Listing title (3–120 characters)"],
        description: Annotated[str | None, "Optional description of the file content (max 500 characters)"] = None,
        tags: Annotated[list[str] | None, "Optional tags for discoverability (max 8, alphanumeric with hyphens)"] = None,
        category: Annotated[str | None, "Optional category: reports, datasets, code, media, models, prompts, or other"] = None,
    ) -> str:
        start = time.monotonic()
        args = {k: v for k, v in {
            "uploadId": uploadId,
            "title": title,
            "description": description,
            "tags": tags,
            "category": category,
        }.items() if v is not None}

        auth = resolve_auth()
        if not auth:
            record_auth_failure()
            audit_log({"tool": TOOL, "result": "auth_failed"})
            raise ValueError("Authentication required. Set AGENTVEE_API_KEY environment variable.")

        ok, msg = check_throttle(TOOL, auth.token_prefix)
        if not ok:
            record_throttle_rejection()
            audit_log({"tool": TOOL, "tokenPrefix": auth.token_prefix, "result": "throttled"})
            raise ValueError(msg)

        body: dict[str, object] = {"uploadId": uploadId, "title": title}
        if description is not None:
            body["description"] = description
        if tags is not None:
            body["tags"] = tags
        if category is not None:
            body["category"] = category

        result = await api_post_json("/v1/agent/marketplace/list", auth.agent_key, body)
        duration_ms = (time.monotonic() - start) * 1000

        if not result.ok:
            record_tool_call(TOOL, duration_ms, True)
            audit_log({
                "tool": TOOL,
                "tokenPrefix": auth.token_prefix,
                "result": "error",
                "errorCode": result.code,
                "durationMs": round(duration_ms),
                "argsDigest": sanitize_args(TOOL, args),
            })
            raise ValueError(result.message)

        data = result.data
        record_tool_call(TOOL, duration_ms, False)
        audit_log({
            "tool": TOOL,
            "tokenPrefix": auth.token_prefix,
            "result": "ok",
            "uploadId": data.get("uploadId"),
            "durationMs": round(duration_ms),
            "argsDigest": sanitize_args(TOOL, args),
        })

        output = {
            "listed": data.get("listed", False),
            "uploadId": data.get("uploadId"),
            "marketplaceUrl": data.get("marketplaceUrl"),
        }
        return json.dumps({k: v for k, v in output.items() if v is not None})
