"""Stobo MCP Server — exposes Stobo API as tools for Claude Desktop."""

from __future__ import annotations

import json
import os

from mcp.server.fastmcp import FastMCP

from stobo.client import StoboAPIError, StoboClient

mcp = FastMCP(
    "Stobo",
    instructions="AI-powered SEO/AEO content optimization tools. Run audits, extract brand voice, optimize content.",
)


def _get_client() -> StoboClient:
    api_key = os.environ.get("STOBO_API_KEY", "")
    base_url = os.environ.get("STOBO_BASE_URL", "https://api.trystobo.com")
    return StoboClient(base_url=base_url, api_key=api_key)


def _call(fn, *args, **kwargs) -> str:
    """Call a client method and return JSON string, handling errors."""
    try:
        result = fn(*args, **kwargs)
        return json.dumps(result, indent=2, default=str)
    except StoboAPIError as e:
        return json.dumps({"error": e.detail, "status_code": e.status_code})
    except Exception as e:
        return json.dumps({"error": str(e)})


# ── Audit Tools ──────────────────────────────────────────────────────


@mcp.tool()
def audit_article(
    url: str,
    keyword: str | None = None,
    use_playwright: bool = False,
) -> str:
    """Run a full SEO + AEO audit on a URL. Returns score, grade, and detailed checker results."""
    client = _get_client()
    return _call(client.audit_article, url, keyword=keyword, use_playwright=use_playwright)


@mcp.tool()
def audit_seo(url: str, keyword: str | None = None) -> str:
    """Run an SEO-only audit on a URL. Returns technical SEO scores and recommendations."""
    client = _get_client()
    return _call(client.audit_seo, url, keyword=keyword)


@mcp.tool()
def audit_aeo(url: str) -> str:
    """Run an AEO-only audit on a URL. Checks AI engine optimization signals."""
    client = _get_client()
    return _call(client.audit_aeo, url)


@mcp.tool()
def get_audit(audit_id: str) -> str:
    """Fetch a previously completed audit by its ID."""
    client = _get_client()
    return _call(client.get_audit, audit_id)


@mcp.tool()
def list_audits(skip: int = 0, limit: int = 20) -> str:
    """List recent audits with pagination."""
    client = _get_client()
    return _call(client.list_audits, skip=skip, limit=limit)


# ── Tone Tools ───────────────────────────────────────────────────────


@mcp.tool()
def extract_tone(
    blog_url: str,
    customer_id: str | None = None,
    max_articles: int = 10,
) -> str:
    """Extract brand voice profile from a blog URL by analyzing its articles."""
    client = _get_client()
    return _call(
        client.extract_tone, blog_url, customer_id=customer_id, max_articles=max_articles
    )


@mcp.tool()
def get_tone(customer_id: str) -> str:
    """Get a stored brand voice/tone profile by customer ID."""
    client = _get_client()
    return _call(client.get_tone, customer_id)


@mcp.tool()
def list_tone_profiles() -> str:
    """List all stored brand voice profiles."""
    client = _get_client()
    return _call(client.list_tone_profiles)


# ── Optimize Tools ───────────────────────────────────────────────────


@mcp.tool()
def optimize(
    url: str,
    customer_id: str | None = None,
    sync: bool = False,
) -> str:
    """Start a full optimization pipeline: audit → tone → rewrite. Returns a job ID to track progress."""
    client = _get_client()
    return _call(client.optimize, url, customer_id=customer_id, sync=sync)


@mcp.tool()
def get_job(job_id: str) -> str:
    """Check the status of an optimization job. Returns progress, status, and results when complete."""
    client = _get_client()
    return _call(client.get_job, job_id)


# ── Freshness Tools ──────────────────────────────────────────────────


@mcp.tool()
def freshness_audit(sitemap_url: str, limit: int = 50) -> str:
    """Audit a sitemap for dateModified schema compliance. Checks content freshness signals."""
    client = _get_client()
    return _call(client.freshness_audit, sitemap_url, limit=limit)


# ── Export Tools ─────────────────────────────────────────────────────


@mcp.tool()
def export_report(
    customer_id: str,
    data_type: str,
) -> str:
    """Generate a markdown export report. data_type can be 'seo', 'aeo', 'tone', or 'full'."""
    client = _get_client()
    return _call(client.export, customer_id, data_type)


def main():
    mcp.run()


if __name__ == "__main__":
    main()
