"""License gating for premium FinAgent Pro features."""

from __future__ import annotations

import json
import os

from mcp_marketplace_license import verify_license


def check_license() -> dict:
    """Check whether a valid FinAgent Pro license key is present.

    Uses the MCP Marketplace License SDK for real validation.
    Supports both MCP_LICENSE_KEY (SDK default) and FINAGENT_LICENSE_KEY (legacy).
    """
    # Support legacy env var as fallback
    if not os.environ.get("MCP_LICENSE_KEY") and os.environ.get("FINAGENT_LICENSE_KEY"):
        os.environ["MCP_LICENSE_KEY"] = os.environ["FINAGENT_LICENSE_KEY"]

    return verify_license(slug="finagent-pro")


def require_license(tool_name: str) -> str | None:
    """Gate a tool behind a license check.

    Args:
        tool_name: Name of the tool being gated (for the error message).

    Returns:
        ``None`` if the license is valid (caller should proceed).
        A JSON error string if the license is missing/invalid (caller should
        return this string directly to the MCP client).
    """
    result = check_license()
    if result.get("valid"):
        return None

    reason = result.get("reason", "unknown")
    return json.dumps({
        "error": "premium_required",
        "reason": reason,
        "message": (
            f"The '{tool_name}' tool requires a FinAgent Pro license. "
            "Set the MCP_LICENSE_KEY environment variable to unlock it. "
            "Get your key at https://mcp-marketplace.io/server/finagent-pro"
        ),
    })
