"""suss. MCP server — scam detection and trust intelligence for AI agents.

Install: pip install suss-mcp
Run:     suss-mcp  (stdio transport for Claude Desktop / Claude Code)

Environment variables:
  SUSS_API_URL  — API base URL (default: production)
  SUSS_API_KEY  — Optional API key for authenticated access
"""

from __future__ import annotations

import json

from mcp.server.fastmcp import FastMCP

from .client import SussClient

mcp = FastMCP(
    "suss",
    description=(
        "Scam detection and trust intelligence. "
        "Check if websites are legitimate, scan text for scams, "
        "look up phone numbers and emails in the scam database."
    ),
)

_client = SussClient()


def _format_trust(data: dict) -> str:
    """Format trust data into a readable summary."""
    level = data.get("trust_level", "unknown")
    score = data.get("trust_score", 0)
    domain = data.get("domain", "")
    summary = data.get("summary", "")
    signals = data.get("signals", [])
    missing = data.get("missing", [])
    risk = data.get("risk_score")

    parts = [f"## {domain}", f"**Trust level:** {level} ({score}/100)"]
    if summary:
        parts.append(f"**Summary:** {summary}")
    if risk is not None:
        parts.append(f"**Risk score:** {risk:.2f}")
    if signals:
        parts.append("**Trust signals:**")
        for s in signals:
            parts.append(f"  - {s}")
    if missing:
        parts.append("**Missing data:**")
        for m in missing:
            parts.append(f"  - {m}")
    return "\n".join(parts)


def _format_scan(data: dict) -> str:
    """Format scan result into a readable summary."""
    score = data.get("score", 0)
    bucket = data.get("bucket", "UNKNOWN")
    signals = data.get("risk_signals", [])
    category = data.get("category", "")
    guidance = data.get("contextual_guidance", {})

    parts = [f"**Scam score:** {score:.2f} ({bucket})"]
    if category:
        parts.append(f"**Category:** {category}")
    if signals:
        parts.append(f"**Risk signals:** {', '.join(signals)}")
    if guidance:
        if guidance.get("what"):
            parts.append(f"**What:** {guidance['what']}")
        if guidance.get("so_what"):
            parts.append(f"**Context:** {guidance['so_what']}")
        if guidance.get("now_what"):
            parts.append("**Recommended actions:**")
            for action in guidance["now_what"]:
                parts.append(f"  - {action}")

    trust = data.get("trust")
    if trust and isinstance(trust, dict):
        level = trust.get("level", trust.get("trust_level", ""))
        t_score = trust.get("score", trust.get("trust_score", 0))
        if level:
            parts.append(f"**Domain trust:** {level} ({t_score}/100)")

    return "\n".join(parts)


def _format_verify(data: dict) -> str:
    """Format fast verify result."""
    score = data.get("score", 0)
    bucket = data.get("bucket", "UNKNOWN")
    signals = data.get("risk_signals", [])
    trust = data.get("trust", {})
    latency = data.get("latency_ms", 0)
    cached = data.get("cached", False)

    parts = [
        f"**Score:** {score:.2f} ({bucket})",
        f"**Latency:** {latency}ms {'(cached)' if cached else ''}",
    ]
    if signals:
        parts.append(f"**Risk signals:** {', '.join(signals)}")
    if trust:
        parts.append(f"**Trust:** {trust.get('level', 'unknown')} ({trust.get('score', 0)}/100)")

    entities = data.get("entities", {})
    if entities:
        for etype, values in entities.items():
            if values:
                parts.append(f"**{etype}:** {', '.join(str(v) for v in values)}")

    entity_risk = data.get("entity_risk", {})
    if entity_risk and entity_risk.get("known_scammer_entities", 0) > 0:
        parts.append(
            f"**Known scammer entities:** {entity_risk['known_scammer_entities']}"
        )

    return "\n".join(parts)


@mcp.tool()
async def check_trust(domain: str) -> str:
    """Check the trust score and reputation of a domain/website.

    Returns trust level (verified/established/moderate/new/unknown/suspicious),
    trust signals, evidence from Trustpilot/WHOIS/ScamAdviser, and risk indicators.

    Use this when someone asks "Is this website legit?" or wants to verify a merchant.

    Args:
        domain: The domain to check (e.g. "amazon.com", "sketchy-store.shop")
    """
    data = await _client.check_trust(domain)
    return _format_trust(data)


@mcp.tool()
async def scan_text(text: str, channel: str = "default") -> str:
    """Scan text for scam indicators. Detects 367+ scam signals across 20+ categories.

    Covers: phishing, romance scams, job scams, crypto fraud, marketplace scams,
    tech support scams, identity theft, AI-powered scams, and more.

    Args:
        text: The suspicious text to analyze (email, message, listing, etc.)
        channel: Context hint — "sms", "email", "marketplace", "social", or "default"
    """
    data = await _client.scan_text(text, channel=channel)
    return _format_scan(data)


@mcp.tool()
async def scan_url(url: str, text: str = "") -> str:
    """Scan a URL for scam indicators, combining domain trust with content analysis.

    Checks domain reputation (Trustpilot, WHOIS, ScamAdviser, Safe Browsing) and
    optionally analyzes text content from the page.

    Args:
        url: The URL to check (e.g. "https://deal-store.shop/product")
        text: Optional page content or surrounding text to analyze alongside the URL
    """
    data = await _client.scan_url(url, text=text)
    return _format_scan(data)


@mcp.tool()
async def batch_trust(domains: list[str]) -> str:
    """Check trust scores for multiple domains at once (up to 50).

    Useful for comparing merchants, vetting a list of websites, or
    checking multiple links from an email.

    Args:
        domains: List of domains to check (max 50)
    """
    if len(domains) > 50:
        return "Error: Maximum 50 domains per batch request."

    data = await _client.batch_trust(domains)
    results = data.get("results", [])

    parts = [f"## Batch Trust Check ({len(results)} domains)\n"]
    for r in results:
        domain = r.get("domain", "")
        level = r.get("trust_level", "unknown")
        score = r.get("trust_score", 0)
        parts.append(f"- **{domain}**: {level} ({score}/100)")

    failed = data.get("failed", 0)
    if failed:
        parts.append(f"\n_{failed} domain(s) failed to resolve._")

    return "\n".join(parts)


@mcp.tool()
async def report_scam(
    request_id: str,
    feedback_type: str,
    original_text: str = "",
    original_score: float = 0.0,
    comment: str = "",
) -> str:
    """Report a false positive or false negative to improve detection.

    Submit feedback on a previous scan result. This helps train the model
    and improve trust scores for everyone.

    Args:
        request_id: The request_id from a previous scan result
        feedback_type: "reported_scam" (false negative) or "dismissed" (false positive) or "confirmed_correct"
        original_text: The text that was scanned (helps with retraining)
        original_score: The score from the original scan
        comment: Optional explanation of why this feedback is being submitted
    """
    valid_types = {"reported_scam", "dismissed", "confirmed_correct"}
    if feedback_type not in valid_types:
        return f"Error: feedback_type must be one of: {', '.join(sorted(valid_types))}"

    data = await _client.report_feedback(
        request_id=request_id,
        feedback_type=feedback_type,
        original_text=original_text,
        original_score=original_score,
        user_comment=comment,
    )
    success = data.get("success", data.get("status") == "ok")
    if success:
        return "Feedback submitted successfully. Thank you for helping improve scam detection."
    return f"Feedback submission failed: {json.dumps(data)}"


@mcp.tool()
async def lookup_entity(entity_type: str, value: str) -> str:
    """Look up a phone number, email, crypto wallet, or payment handle in the scam database.

    Checks if the entity has been previously reported in scam incidents.
    Returns report count, risk level, associated scam types, and linked entities.

    Args:
        entity_type: Type of entity — "phone", "email", "wallet", "domain", or "payment_handle"
        value: The entity value (e.g. "+15551234567", "scammer@mail.com", "bc1q...")
    """
    valid_types = {"phone", "email", "wallet", "domain", "payment_handle"}
    if entity_type not in valid_types:
        return f"Error: entity_type must be one of: {', '.join(sorted(valid_types))}"

    data = await _client.lookup_entity(entity_type, value)

    found = data.get("found", False)
    if not found:
        return f"No reports found for {entity_type}: {value}. This entity is not in the scam database (which doesn't guarantee it's safe)."

    parts = [
        f"## Entity Report: {value}",
        f"**Type:** {entity_type}",
        f"**Risk level:** {data.get('risk_level', 'unknown')}",
        f"**Risk score:** {data.get('risk_score', 0):.2f}",
        f"**Times reported:** {data.get('times_reported', 0)}",
    ]

    scam_types = data.get("scam_types", [])
    if scam_types:
        parts.append(f"**Associated scam types:** {', '.join(scam_types)}")

    first_seen = data.get("first_seen")
    last_seen = data.get("last_seen")
    if first_seen:
        parts.append(f"**First seen:** {first_seen}")
    if last_seen:
        parts.append(f"**Last seen:** {last_seen}")

    linked = data.get("linked_entities", [])
    if linked:
        parts.append("**Linked entities:**")
        for ent in linked[:10]:
            parts.append(f"  - {ent.get('type', '')}: {ent.get('value', '')}")

    return "\n".join(parts)


@mcp.tool()
async def verify(text: str = "", url: str = "", include_image: bool = False) -> str:
    """Fast verification optimized for AI agents. Returns structured data only, no prose.

    Skips comprehension layer and guidance generation for sub-200ms response times.
    Use this for high-volume automated checks where speed matters more than explanation.

    Args:
        text: Text to scan for scam indicators
        url: URL to check trust and reputation
        include_image: Set to true to include image analysis (adds ~1-2s latency)
    """
    if not text and not url:
        return "Error: Provide at least one of 'text' or 'url'."

    data = await _client.verify(text=text, url=url, include_image=include_image)
    return _format_verify(data)


def main() -> None:
    """Entry point for the suss-mcp CLI."""
    mcp.run()


if __name__ == "__main__":
    main()
