"""MCP Prompts for Meta Ads MCP Server.

Provides pre-defined AI prompts for common advertising workflows.
Prompts guide AI assistants through complex multi-step operations.

MCP SDK v1.x Feature: Prompts decorator for workflow guidance.
"""
from __future__ import annotations

from typing import TYPE_CHECKING

from mcp.server.fastmcp import FastMCP
from mcp import types as mcp_types

from .logging import get_logger

if TYPE_CHECKING:
    pass

logger = get_logger(__name__)


def register_prompts(mcp: FastMCP) -> None:
    """Register all MCP prompts with the server."""

    @mcp.prompt("campaign_optimizer")
    def campaign_optimization_prompt() -> list[mcp_types.PromptMessage]:
        """Prompt for analyzing and optimizing campaign performance.
        
        Guides AI through a comprehensive campaign optimization workflow.
        """
        return [
            mcp_types.PromptMessage(
                role="user",
                content=mcp_types.TextContent(
                    type="text",
                    text="""Please analyze and optimize my Meta Ads campaigns. Follow this workflow:

1. DISCOVERY
   - Use meta.campaign.list to get all active campaigns
   - Use meta.ads.insights to fetch last 7 days performance data
   - Identify top 3 performers and bottom 3 underperformers

2. DIAGNOSIS  
   - For underperformers, use meta.health.detect_creative_fatigue_radar
   - Check audience saturation with meta.health.measure_audience_exhaustion
   - Analyze budget pacing with meta.tactical.monitor_budget_burn_rate

3. RECOMMENDATIONS
   - Use meta.tactical.recommend_top_5_actions for AI-powered suggestions
   - Calculate optimal budget reallocation
   - Identify creative refresh candidates

4. ACTION PLAN
   - Provide specific, actionable recommendations
   - Prioritize by urgency × impact
   - Include expected performance improvements

Please start by listing my campaigns."""
                )
            )
        ]

    @mcp.prompt("fraud_detector")  
    def fraud_detection_prompt() -> list[mcp_types.PromptMessage]:
        """Prompt for running comprehensive fraud analysis workflow.
        
        Detects bot traffic, invalid conversions, and security threats.
        """
        return [
            mcp_types.PromptMessage(
                role="user",
                content=mcp_types.TextContent(
                    type="text",
                    text="""Please run a comprehensive fraud analysis on my ad account. Follow this workflow:

1. CLICK PATTERN ANALYSIS
   - Use meta.fraud.analyze_click_patterns to detect bot farm activity
   - Flag geographic and temporal anomalies
   - Check for suspicious click clustering

2. CONVERSION FRAUD DETECTION
   - Use meta.fraud.detect_conversion_fraud to identify fake conversions
   - Analyze device fingerprinting patterns
   - Check conversion rate anomalies vs benchmarks

3. PLACEMENT QUALITY
   - Use meta.fraud.score_placement_quality to evaluate delivering placements
   - Identify fraud-prone placements
   - Generate exclusion list recommendations

4. INVALID TRAFFIC FILTERING
   - Use meta.fraud.filter_invalid_traffic for MRC-compliant IVT filtering
   - Calculate wasted spend on invalid traffic
   - Estimate recovery potential

5. SECURITY MONITORING
   - Use meta.fraud.monitor_account_security for security threats
   - Check for unauthorized access attempts
   - Review account permission changes

Please provide a comprehensive fraud report with estimated savings and recommended actions."""
                )
            )
        ]

    @mcp.prompt("budget_optimizer")
    def budget_optimization_prompt() -> list[mcp_types.PromptMessage]:
        """Prompt for optimizing portfolio budget allocation.
        
        Reallocates budget across campaigns for maximum ROAS.
        """
        return [
            mcp_types.PromptMessage(
                role="user",
                content=mcp_types.TextContent(
                    type="text",
                    text="""Please optimize my portfolio budget allocation. Follow this workflow:

1. PORTFOLIO ANALYSIS
   - Use meta.budget.optimize_portfolio_budget to analyze current allocation
   - Calculate performance-weighted distribution
   - Identify budget efficiency by campaign

2. MARGINAL ROAS CALCULATION
   - Use meta.budget.calculate_marginal_roas for each campaign
   - Determine diminishing returns thresholds
   - Find optimal budget levels

3. CEILING DETECTION
   - Use meta.budget.detect_campaign_ceiling for top performers
   - Identify maximum viable budget before saturation
   - Flag campaigns hitting ceilings

4. UNDERDELIVERY RESCUE
   - Use meta.budget.rescue_underdelivering_campaigns
   - Diagnose delivery issues
   - Recommend fixes for pacing problems

5. REALLOCATION PLAN
   - Generate optimal budget reallocation
   - Calculate expected ROAS improvement
   - Provide implementation timeline

Please analyze my current budget and provide specific reallocation recommendations."""
                )
            )
        ]

    @mcp.prompt("v24_compliance_check")
    def v24_compliance_prompt() -> list[mcp_types.PromptMessage]:
        """Prompt for checking v24.0 API compliance status.
        
        Reviews campaigns for v24.0 breaking changes.
        """
        return [
            mcp_types.PromptMessage(
                role="user",
                content=mcp_types.TextContent(
                    type="text",
                    text="""Please check my ad account for Meta Marketing API v24.0 compliance issues. Follow this workflow:

1. FLAGGED AUDIENCE CHECK
   - List all custom audiences
   - Use meta.audience.check_flagged for each audience
   - Report flagged audiences with resolution steps

2. FLAGGED CONVERSION CHECK
   - List all custom conversions
   - Use meta.conversion.check_flagged for each conversion
   - Report flagged conversions with resolution steps

3. ADVANTAGE+ MIGRATION STATUS
   - Check for old ASC/AAC campaigns that need migration
   - Use meta.advantage.migrate_to_advantage_plus where needed
   - Verify dynamic_media_default usage for catalog flows

4. PLACEMENT COMPLIANCE
   - Check for campaigns using deprecated Facebook video feeds
   - Recommend migration to Reels placement

5. BUDGET CONFIGURATION
   - Check campaigns for is_adset_budget_sharing_enabled field
   - Validate budget-change guidance with +/-75% flexibility

6. CTMLG READINESS
   - Identify legacy CTMLG dependencies
   - Provide migration plan to supported APIs

Please provide a v24.0 compliance report with action items prioritized by urgency and current release-note risk."""
                )
            )
        ]

    @mcp.prompt("executive_dashboard")
    def executive_dashboard_prompt() -> list[mcp_types.PromptMessage]:
        """Prompt for generating executive-ready performance dashboards.
        
        Creates CEO/CFO/Board-ready reports.
        """
        return [
            mcp_types.PromptMessage(
                role="user",
                content=mcp_types.TextContent(
                    type="text",
                    text="""Please generate an executive dashboard for my Meta Ads performance. Follow this workflow:

1. CEO DASHBOARD
   - Use meta.executive.generate_ceo_dashboard for top 5 strategic metrics
   - Include ROAS, CAC, efficiency, scale, and revenue data
   - Provide period-over-period trends

2. CFO FINANCIAL REPORT
   - Use meta.executive.generate_cfo_financial_report for P&L analysis
   - Include cash flow impact and working capital analysis
   - Calculate marketing contribution to revenue

3. BOARD PRESENTATION DATA
   - Use meta.executive.generate_board_presentation for board-ready metrics
   - Include investment justification
   - Show competitive positioning

4. RECOMMENDATIONS
   - Budget increase justification (if warranted)
   - Risk factors and mitigations
   - Strategic opportunities

Please create a complete executive report suitable for the next board meeting."""
                )
            )
        ]

    logger.info("Registered MCP prompts")
