"""License key validation for MixLift MCP Server."""

from __future__ import annotations

from dataclasses import dataclass

import httpx

VALIDATE_URL = "https://api.mixlift.io/v1/license/validate"

# Tier limits
FREE_MAX_CHANNELS = 2
FREE_MAX_ROWS = 2_000
PRO_MAX_CHANNELS = 8
PRO_MAX_ROWS = 50_000


@dataclass
class LicenseStatus:
    is_pro: bool
    max_channels: int
    max_rows: int
    message: str


def free_tier(message: str = "Free tier") -> LicenseStatus:
    return LicenseStatus(
        is_pro=False,
        max_channels=FREE_MAX_CHANNELS,
        max_rows=FREE_MAX_ROWS,
        message=message,
    )


async def validate_license(license_key: str | None) -> LicenseStatus:
    """Validate a license key against the remote endpoint.

    Returns free tier if key is missing, invalid, or endpoint unreachable.
    """
    if not license_key:
        return free_tier("No license key provided")

    try:
        async with httpx.AsyncClient(timeout=5.0) as client:
            response = await client.post(
                VALIDATE_URL,
                json={"license_key": license_key},
            )
            response.raise_for_status()
            data = response.json()

            if data.get("valid") and data.get("tier") in ("pro", "growth"):
                return LicenseStatus(
                    is_pro=True,
                    max_channels=PRO_MAX_CHANNELS,
                    max_rows=PRO_MAX_ROWS,
                    message="Pro license validated",
                )
            return free_tier("Invalid license key")

    except Exception:
        return free_tier("License validation unavailable — using free tier")
