"""HeyLead MCP Server — the heart of the product.

Registers all 5 tools and runs via stdio transport for Claude Code / Cursor.

Usage:
    claude mcp add heylead -- python -m heylead
    # or after PyPI publish:
    claude mcp add heylead -- uvx heylead
"""

from __future__ import annotations

import logging
import logging.handlers
import sys
from pathlib import Path
from typing import Optional

from mcp.server.fastmcp import FastMCP

from . import __version__, config

# ──────────────────────────────────────────────
# Logging (MUST go to stderr/file, NEVER stdout — breaks MCP stdio)
# ──────────────────────────────────────────────

def _setup_logging() -> None:
    """Configure logging to file + stderr. Never stdout."""
    config.ensure_dirs()
    log_file = config.log_path()

    root_logger = logging.getLogger("heylead")
    root_logger.setLevel(logging.DEBUG)

    # File handler (rotating, 10 MB)
    file_handler = logging.handlers.RotatingFileHandler(
        str(log_file),
        maxBytes=10 * 1024 * 1024,
        backupCount=3,
    )
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(
        logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
    )
    root_logger.addHandler(file_handler)

    # Stderr handler (warnings and above only)
    stderr_handler = logging.StreamHandler(sys.stderr)
    stderr_handler.setLevel(logging.WARNING)
    stderr_handler.setFormatter(logging.Formatter("[%(levelname)s] %(message)s"))
    root_logger.addHandler(stderr_handler)


# ──────────────────────────────────────────────
# Initialize MCP Server
# ──────────────────────────────────────────────

_setup_logging()
logger = logging.getLogger(__name__)

mcp = FastMCP(
    "heylead",
    instructions=(
        "HeyLead — Your AI sales rep. MCP-native autonomous LinkedIn SDR. "
        "One command to fill your pipeline. "
        "Use setup_profile first, then create_campaign, generate_and_send, "
        "check_replies, and show_status."
    ),
)


# ──────────────────────────────────────────────
# Tool 1: setup_profile
# ──────────────────────────────────────────────

@mcp.tool()
async def setup_profile(
    llm_api_key: str = "",
    llm_provider: str = "gemini",
    backend_url: str = "",
    backend_jwt: str = "",
) -> str:
    """Analyze your LinkedIn profile and generate a voice signature.

    This analyzes your LinkedIn profile, posts, and writing style to create
    a "voice signature" — so every outreach message sounds like YOU, not a bot.

    Args:
        llm_api_key: API key for AI (Gemini recommended — free at aistudio.google.com/apikey).
            Only needed on first setup. Stored locally after that.
        llm_provider: Which AI to use: "gemini" (recommended), "claude", or "openai".
        backend_url: HeyLead Backend API URL (e.g. https://heylead-api-xxx.run.app).
            Enables backend mode where Unipile credentials stay server-side.
        backend_jwt: Your authentication token from the HeyLead backend.
            Get it by signing in at: <backend_url>/auth/login-url
    """
    from .tools.setup_profile import run_setup_profile

    logger.info("Running setup_profile")
    try:
        result = await run_setup_profile(
            llm_api_key=llm_api_key,
            llm_provider=llm_provider,
            backend_url=backend_url,
            backend_jwt=backend_jwt,
        )
        logger.info("setup_profile completed")
        return result
    except Exception as e:
        logger.error(f"setup_profile failed: {e}", exc_info=True)
        return f"❌ Setup failed: {e}\n\nCheck ~/.heylead/logs/heylead.log for details."


# ──────────────────────────────────────────────
# Tool 2: create_campaign
# ──────────────────────────────────────────────

@mcp.tool()
async def create_campaign(
    target_description: str,
    campaign_name: str = "",
) -> str:
    """Create a LinkedIn outreach campaign from a natural language description.

    Describe your ideal customers and HeyLead will find them on LinkedIn.

    Args:
        target_description: Who to target (e.g., "CTOs at fintech startups",
            "freelance UX designers in London", "yoga studio owners in California")
        campaign_name: Optional name for the campaign.
    """
    from .tools.create_campaign import run_create_campaign

    logger.info(f"Running create_campaign: {target_description}")
    try:
        return await run_create_campaign(target_description, campaign_name)
    except Exception as e:
        logger.error(f"create_campaign failed: {e}", exc_info=True)
        return f"❌ Campaign creation failed: {e}"


# ──────────────────────────────────────────────
# Tool 3: generate_and_send
# ──────────────────────────────────────────────

@mcp.tool()
async def generate_and_send(
    campaign_id: str = "",
    mode: str = "copilot",
) -> str:
    """Generate a personalized LinkedIn message and send it (or queue for review).

    In Copilot mode (default): shows the message for your approval before sending.
    In Autopilot mode: sends automatically after validation.

    Args:
        campaign_id: Which campaign to send from. Uses active campaign if empty.
        mode: "copilot" (review first) or "autopilot" (send automatically).
    """
    from .tools.generate_send import run_generate_and_send

    logger.info(f"Running generate_and_send: campaign={campaign_id}, mode={mode}")
    try:
        return await run_generate_and_send(campaign_id, mode)
    except Exception as e:
        logger.error(f"generate_and_send failed: {e}", exc_info=True)
        return f"❌ Message generation failed: {e}"


# ──────────────────────────────────────────────
# Tool 4: check_replies
# ──────────────────────────────────────────────

@mcp.tool()
async def check_replies() -> str:
    """Check for new LinkedIn replies across all campaigns.

    Fetches new messages, classifies sentiment (positive/negative/question),
    and surfaces hot leads that need your attention.
    """
    from .tools.check_replies import run_check_replies

    logger.info("Running check_replies")
    try:
        return await run_check_replies()
    except Exception as e:
        logger.error(f"check_replies failed: {e}", exc_info=True)
        return f"❌ Reply check failed: {e}"


# ──────────────────────────────────────────────
# Tool 5: show_status
# ──────────────────────────────────────────────

@mcp.tool()
async def show_status(
    campaign_id: str = "",
) -> str:
    """Show your outreach dashboard — campaigns, stats, hot leads, account health.

    The chat IS your dashboard. Ask "how's my outreach?" anytime.

    Args:
        campaign_id: Show stats for a specific campaign. Shows all if empty.
    """
    from .tools.show_status import run_show_status

    logger.info("Running show_status")
    try:
        return await run_show_status(campaign_id)
    except Exception as e:
        logger.error(f"show_status failed: {e}", exc_info=True)
        return f"❌ Status check failed: {e}"


# ──────────────────────────────────────────────
# Entry point
# ──────────────────────────────────────────────

def main() -> None:
    """Run the HeyLead MCP server (stdio transport)."""
    logger.info(f"Starting HeyLead MCP server v{__version__}")

    # Ensure directories and DB exist on first run
    config.ensure_dirs()

    # Initialize the database
    from .db.schema import get_db
    db = get_db()
    db.close()

    # Run MCP server
    mcp.run(transport="stdio")
