# Beamt, LLC - CONFIDENTIAL
# Copyright (c) 2026 Beamt, LLC. All rights reserved.
#
# This file is the proprietary property of Beamt, LLC.
# Unauthorized reproduction or distribution is strictly prohibited.

"""Preflight MCP Server — TrustPilot for APIs, built for AI agents."""

import httpx
import os
from fastmcp import FastMCP

PREFLIGHT_API = os.getenv("PREFLIGHT_API_URL", "https://preflight.beamt.io")
PREFLIGHT_KEY = os.getenv("PREFLIGHT_API_KEY", "")

mcp = FastMCP(
    "Preflight",
    instructions="TrustPilot for APIs. Look up independent reliability ratings for any API or MCP server — uptime, latency, error rates, and community reviews from real agent traffic. Use Preflight to decide which services to trust.",
)


def _headers():
    if PREFLIGHT_KEY:
        return {"Authorization": f"Bearer {PREFLIGHT_KEY}"}

    return {}


@mcp.tool
async def check_reliability(
    service: str,
    metrics: list[str] | None = None,
) -> dict:
    """Look up the independent reliability rating for an API or MCP server.
    Like checking a restaurant's reviews before booking — see the real uptime,
    latency, error rate, and community experience before you commit to a service.

    Returns a trust score (0-100), current operational status, trend direction,
    and any known issues. Scores are based on independent synthetic probes and
    crowdsourced telemetry from real agent traffic — not vendor self-reporting.

    Args:
        service: Service slug (e.g., 'stripe-mcp', 'openai-api') or partial name
        metrics: Optional list of specific metrics to include:
                 'uptime', 'latency', 'reliability', 'maintenance', 'community'
    """

    params = {"service": service}

    if metrics:
        params["metrics"] = ",".join(metrics)

    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.get(
                f"{PREFLIGHT_API}/v1/score", params=params, headers=_headers()
            )

            resp.raise_for_status()

            return resp.json()
    except httpx.HTTPStatusError as exc:
        return {
            "error": True,
            "status_code": exc.response.status_code,
            "detail": exc.response.text,
        }
    except (httpx.ConnectError, httpx.TimeoutException) as exc:
        return {
            "error": True,
            "status_code": None,
            "detail": f"Connection failed: {exc}",
        }


@mcp.tool
async def compare_services(
    services: list[str],
    sort_by: str = "overall",
) -> dict:
    """Compare reliability ratings across multiple services side by side.
    Like reading comparative reviews — see which provider has the best track
    record for uptime, latency, and real-world reliability right now.

    Returns services ranked by the chosen metric with a recommendation
    and the reasoning behind it.

    Args:
        services: List of service slugs to compare (max 10)
        sort_by: Metric to sort by — 'overall', 'uptime', 'latency', 'reliability'
    """

    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.get(
                f"{PREFLIGHT_API}/v1/compare",
                params={"services": ",".join(services), "sort_by": sort_by},
                headers=_headers(),
            )

            resp.raise_for_status()

            return resp.json()
    except httpx.HTTPStatusError as exc:
        return {
            "error": True,
            "status_code": exc.response.status_code,
            "detail": exc.response.text,
        }
    except (httpx.ConnectError, httpx.TimeoutException) as exc:
        return {
            "error": True,
            "status_code": None,
            "detail": f"Connection failed: {exc}",
        }


@mcp.tool
async def report_outcome(
    service: str,
    outcome: str,
    latency_ms: int | None = None,
    error_type: str | None = None,
) -> dict:
    """Leave a review — report the outcome of an API or MCP server call you
    just made. Like writing a TrustPilot review, your report contributes to
    the community reliability rating for that service.

    The more agents that report, the more accurate the ratings become for everyone.

    Args:
        service: Service slug that was called
        outcome: Result — 'success', 'error', 'timeout', or 'unexpected'
        latency_ms: Response time in milliseconds (if available)
        error_type: If outcome was 'error', the category:
                    'auth', 'rate_limit', 'server', 'network', 'parse', 'other'
    """

    payload = {"service": service, "outcome": outcome}

    if latency_ms is not None:
        payload["latency_ms"] = latency_ms

    if error_type is not None:
        payload["error_type"] = error_type

    try:
        async with httpx.AsyncClient(timeout=10) as client:
            resp = await client.post(
                f"{PREFLIGHT_API}/v1/report",
                json=payload,
                headers=_headers(),
            )

            resp.raise_for_status()

            return resp.json()
    except httpx.HTTPStatusError as exc:
        return {
            "error": True,
            "status_code": exc.response.status_code,
            "detail": exc.response.text,
        }
    except (httpx.ConnectError, httpx.TimeoutException) as exc:
        return {
            "error": True,
            "status_code": None,
            "detail": f"Connection failed: {exc}",
        }


def main():
    mcp.run()
