"""Minimal MCP server (stdio) exposing the Better Vetters API to agents.

Env:  CONTRACTOR_CHECK_API_URL or BETTER_VETTERS_API_URL (default http://localhost:8080)
      CONTRACTOR_CHECK_API_KEY or BETTER_VETTERS_API_KEY (required for checks)
Run:  python server.py
"""
import json
import os
import uuid

import httpx
try:  # mcp >= 2.0
    from mcp.server.mcpserver import MCPServer as FastMCP
except ImportError:  # mcp 1.x
    from mcp.server.fastmcp import FastMCP

BASE = (os.environ.get("CONTRACTOR_CHECK_API_URL") or os.environ.get("BETTER_VETTERS_API_URL") or "http://localhost:8080").rstrip("/")
KEY = os.environ.get("CONTRACTOR_CHECK_API_KEY") or os.environ.get("BETTER_VETTERS_API_KEY") or ""

mcp = FastMCP("better-vetters")


@mcp.tool()
def check_contractor(name: str, state: str | None = None, city: str | None = None, license_number: str | None = None,
                     phone: str | None = None, website: str | None = None) -> str:
    """Check whether a US contractor is real, licensed and pulling permits, from public records.

    Returns JSON with verdict, trust_score (0-100 or null), match.confidence, licence status/type/expiry, discipline,
    recent permit count + samples, reasons, and data freshness. Costs about $0.15 per call (billed to the API key).
    Covered: WA (all L&I contractors + Seattle permits), TX (TDLR electrical/A-C + Austin permits), NY (NYC home improvement
    licences + DOB permits). Provide `state` whenever you know it. Treat match.confidence < 0.8 as a possible match only.
    """
    if not KEY:
        return json.dumps({"error": "CONTRACTOR_CHECK_API_KEY is not set (alias: BETTER_VETTERS_API_KEY). Create a free key with POST /v1/keys."})
    body = {k: v for k, v in dict(name=name, state=state, city=city, license_number=license_number, phone=phone, website=website).items() if v}
    r = httpx.post(f"{BASE}/v1/contractor/check", json=body, headers={"Authorization": f"Bearer {KEY}", "Idempotency-Key": str(uuid.uuid4())}, timeout=30)
    return json.dumps(r.json(), indent=2) if r.headers.get("content-type", "").startswith("application/json") else r.text


@mcp.tool()
def get_coverage() -> str:
    """List covered states/jurisdictions, data sources, record counts, licences and freshness (free)."""
    r = httpx.get(f"{BASE}/v1/coverage", timeout=30)
    return json.dumps(r.json(), indent=2)


if __name__ == "__main__":
    mcp.run()
