"""
Multi-Platform Integration Tools for Meta Ads MCP Server

This module provides tools for WhatsApp, Messenger, and Instagram Direct campaigns
with unified cross-platform orchestration and multi-advertiser campaigns.

Based on Meta Marketing API messaging and partnership features:
https://developers.facebook.com/docs/marketing-api
"""

from __future__ import annotations

from typing import Dict, Any, Optional

from .errors import MetaApiError
from .logging import get_logger
from .meta_client import MetaClient
from .schemas import ToolResult

logger = get_logger(__name__)


class MultiPlatformEngine:
    """Handles multi-platform campaign operations for Meta Ads"""
    
    def __init__(self, client: MetaClient):
        self.client = client
    
    async def create_whatsapp_campaign(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Create Click-to-WhatsApp campaign.
        
        Drive conversations and conversions through WhatsApp messaging.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "campaign_name": "WhatsApp Campaign",
                "page_id": "456",
                "whatsapp_number": "+1234567890",
                "welcome_message": "Hi! How can we help you today?",
                "daily_budget": 5000,
                "targeting": {
                    "countries": ["US"],
                    "age_min": 25,
                    "age_max": 54
                },
                "creative": {
                    "headline": "Chat with us on WhatsApp",
                    "description": "Get instant support",
                    "image_hash": "abc123"
                }
            }
        
        Returns:
            ToolResult with WhatsApp campaign details
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            campaign_name = arguments.get("campaign_name")
            page_id = arguments.get("page_id")
            
            if not all([ad_account_id, campaign_name, page_id]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id, campaign_name, and page_id are required"}
                )
            
            logger.info(f"Creating WhatsApp campaign: {campaign_name}")
            
            # Create campaign with messaging objective
            campaign_data = {
                "name": campaign_name,
                "objective": "OUTCOME_ENGAGEMENT",
                "status": "PAUSED",
                "special_ad_categories": []
            }
            
            campaign_response = await self.client.post(
                f"{ad_account_id}/campaigns",
                body=campaign_data
            )
            campaign_id = campaign_response.get("id")
            
            # Create ad set with WhatsApp destination
            targeting = arguments.get("targeting", {})
            targeting.update({
                "geo_locations": {
                    "countries": targeting.get("countries", ["US"])
                }
            })
            
            adset_data = {
                "name": f"{campaign_name} - AdSet",
                "campaign_id": campaign_id,
                "daily_budget": arguments.get("daily_budget", 5000),
                "billing_event": "IMPRESSIONS",
                "optimization_goal": "CONVERSATIONS",
                "bid_strategy": "LOWEST_COST_WITHOUT_CAP",
                "targeting": targeting,
                "status": "PAUSED",
                "promoted_object": {
                    "page_id": page_id,
                    "whatsapp_number": arguments.get("whatsapp_number")
                }
            }
            
            adset_response = await self.client.post(
                f"{ad_account_id}/adsets",
                body=adset_data
            )
            adset_id = adset_response.get("id")
            
            # Create ad creative with WhatsApp CTA
            creative_data = arguments.get("creative", {})
            
            ad_creative_data = {
                "name": f"{campaign_name} - Creative",
                "object_story_spec": {
                    "page_id": page_id,
                    "link_data": {
                        "message": creative_data.get("description", "Chat with us"),
                        "link": f"https://wa.me/{arguments.get('whatsapp_number', '').replace('+', '')}",
                        "name": creative_data.get("headline", "Message us on WhatsApp"),
                        "call_to_action": {
                            "type": "MESSAGE_PAGE",
                            "value": {
                                "whatsapp_number": arguments.get("whatsapp_number")
                            }
                        },
                        "picture": creative_data.get("image_hash")
                    }
                }
            }
            
            creative_response = await self.client.post(
                f"{ad_account_id}/adcreatives",
                body=ad_creative_data
            )
            creative_id = creative_response.get("id")
            
            # Create ad
            ad_data = {
                "name": f"{campaign_name} - Ad",
                "adset_id": adset_id,
                "creative": {"creative_id": creative_id},
                "status": "PAUSED"
            }
            
            ad_response = await self.client.post(
                f"{ad_account_id}/ads",
                body=ad_data
            )
            ad_id = ad_response.get("id")
            
            return ToolResult(
                ok=True,
                data={
                    "campaign_id": campaign_id,
                    "adset_id": adset_id,
                    "ad_id": ad_id,
                    "creative_id": creative_id,
                    "platform": "whatsapp",
                    "whatsapp_number": arguments.get("whatsapp_number"),
                    "welcome_message": arguments.get("welcome_message"),
                    "status": "PAUSED",
                    "optimization_tips": [
                        "Set up automated responses for common questions",
                        "Train team to respond within 1 hour",
                        "Use WhatsApp Business API for automation",
                        "Track conversation quality and conversion rate",
                        "Enable chatbot for after-hours support"
                    ],
                    "expected_metrics": {
                        "response_rate": "60-80%",
                        "conversation_to_sale": "15-25%",
                        "cost_per_conversation": "$0.50-$2.00"
                    },
                    "next_steps": [
                        "Verify WhatsApp Business account connection",
                        "Set up automated greeting messages",
                        "Configure chatbot flow",
                        "Train support team",
                        "Activate campaign when ready"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_whatsapp_campaign_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_whatsapp_campaign_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def create_messenger_lead_campaign(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Create Messenger lead generation campaign.
        
        Collect leads through automated Messenger conversations.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "campaign_name": "Messenger Lead Gen",
                "page_id": "456",
                "daily_budget": 5000,
                "lead_form_questions": [
                    {"type": "EMAIL", "label": "Email Address"},
                    {"type": "PHONE", "label": "Phone Number"}
                ],
                "qualification_questions": [
                    {"question": "What's your budget?", "options": ["<$1000", "$1000-$5000", ">$5000"]}
                ]
            }
        
        Returns:
            ToolResult with Messenger lead campaign details
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            campaign_name = arguments.get("campaign_name")
            page_id = arguments.get("page_id")
            
            if not all([ad_account_id, campaign_name, page_id]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id, campaign_name, and page_id are required"}
                )
            
            logger.info(f"Creating Messenger lead campaign: {campaign_name}")
            
            # Create campaign
            campaign_data = {
                "name": campaign_name,
                "objective": "OUTCOME_LEADS",
                "status": "PAUSED",
                "special_ad_categories": []
            }
            
            campaign_response = await self.client.post(
                f"{ad_account_id}/campaigns",
                body=campaign_data
            )
            campaign_id = campaign_response.get("id")
            
            # Create ad set
            adset_data = {
                "name": f"{campaign_name} - AdSet",
                "campaign_id": campaign_id,
                "daily_budget": arguments.get("daily_budget", 5000),
                "billing_event": "IMPRESSIONS",
                "optimization_goal": "LEAD_GENERATION",
                "bid_strategy": "LOWEST_COST_WITHOUT_CAP",
                "targeting": arguments.get("targeting", {
                    "geo_locations": {"countries": ["US"]},
                    "age_min": 25,
                    "age_max": 65
                }),
                "status": "PAUSED",
                "promoted_object": {
                    "page_id": page_id
                }
            }
            
            adset_response = await self.client.post(
                f"{ad_account_id}/adsets",
                body=adset_data
            )
            adset_id = adset_response.get("id")
            
            return ToolResult(
                ok=True,
                data={
                    "campaign_id": campaign_id,
                    "adset_id": adset_id,
                    "platform": "messenger",
                    "lead_form_configured": True,
                    "automation_features": [
                        "Automated lead qualification",
                        "Instant lead delivery to CRM",
                        "Follow-up message scheduling",
                        "Lead scoring based on responses",
                        "Hot lead alerts to sales team"
                    ],
                    "expected_metrics": {
                        "cost_per_lead": "$5-15",
                        "lead_quality_score": "7-9/10",
                        "conversation_completion_rate": "60-75%"
                    },
                    "integration_options": [
                        "Zapier integration for CRM sync",
                        "Webhooks for real-time lead delivery",
                        "CSV export for batch processing",
                        "Native CRM integrations (Salesforce, HubSpot)"
                    ],
                    "best_practices": [
                        "Keep conversation flow short (3-5 questions)",
                        "Ask qualifying questions early",
                        "Provide instant value (discount, guide)",
                        "Follow up within 5 minutes for hot leads",
                        "A/B test different conversation flows"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_messenger_lead_campaign_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_messenger_lead_campaign_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def create_instagram_direct_campaign(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Create Instagram Direct (DM) campaign.
        
        Drive engagement through Instagram Direct messages.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "campaign_name": "Instagram DM Campaign",
                "instagram_account_id": "456",
                "daily_budget": 5000,
                "offer_type": "discount_code",  # or "consultation", "demo"
                "offer_details": {
                    "code": "INSTA20",
                    "discount": "20%"
                }
            }
        
        Returns:
            ToolResult with Instagram Direct campaign details
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            campaign_name = arguments.get("campaign_name")
            instagram_account_id = arguments.get("instagram_account_id")
            
            if not all([ad_account_id, campaign_name, instagram_account_id]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id, campaign_name, and instagram_account_id are required"}
                )
            
            logger.info(f"Creating Instagram Direct campaign: {campaign_name}")
            
            offer_type = arguments.get("offer_type", "discount_code")
            offer_details = arguments.get("offer_details", {})
            
            # Create campaign
            campaign_data = {
                "name": campaign_name,
                "objective": "OUTCOME_ENGAGEMENT",
                "status": "PAUSED"
            }
            
            campaign_response = await self.client.post(
                f"{ad_account_id}/campaigns",
                body=campaign_data
            )
            campaign_id = campaign_response.get("id")
            
            # Create ad set
            adset_data = {
                "name": f"{campaign_name} - AdSet",
                "campaign_id": campaign_id,
                "daily_budget": arguments.get("daily_budget", 5000),
                "billing_event": "IMPRESSIONS",
                "optimization_goal": "CONVERSATIONS",
                "targeting": arguments.get("targeting", {
                    "geo_locations": {"countries": ["US"]},
                    "age_min": 18,
                    "age_max": 44  # Instagram skews younger
                }),
                "status": "PAUSED",
                "promoted_object": {
                    "instagram_actor_id": instagram_account_id
                }
            }
            
            adset_response = await self.client.post(
                f"{ad_account_id}/adsets",
                body=adset_data
            )
            adset_id = adset_response.get("id")
            
            return ToolResult(
                ok=True,
                data={
                    "campaign_id": campaign_id,
                    "adset_id": adset_id,
                    "platform": "instagram_direct",
                    "offer_type": offer_type,
                    "offer_details": offer_details,
                    "automated_responses": {
                        "greeting": "Hey! Thanks for messaging us 👋",
                        "offer_delivery": f"Here's your exclusive {offer_details.get('discount', '20%')} off code: {offer_details.get('code', 'SAVE20')}",
                        "follow_up": "Have questions? Reply anytime!"
                    },
                    "engagement_features": [
                        "Story swipe-up to DM",
                        "Feed post DM CTA",
                        "Automated coupon delivery",
                        "Product inquiry handling",
                        "Appointment booking"
                    ],
                    "targeting_tips": [
                        "Target engaged followers first",
                        "Use lookalike of engaged users",
                        "Focus on 18-34 age group",
                        "Target Instagram power users",
                        "Exclude recent converters"
                    ],
                    "expected_performance": {
                        "dm_open_rate": "70-85%",
                        "code_redemption_rate": "20-35%",
                        "cost_per_dm": "$0.30-$1.00"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_instagram_direct_campaign_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_instagram_direct_campaign_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def orchestrate_cross_platform(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Orchestrate unified messaging strategy across platforms.
        
        Coordinate Facebook, Instagram, WhatsApp, and Messenger campaigns
        with unified budget allocation and cross-channel attribution.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "strategy_name": "Multi-Platform Messaging",
                "total_daily_budget": 10000,
                "platforms": {
                    "facebook_messenger": {"enabled": true, "budget_percent": 30},
                    "instagram_direct": {"enabled": true, "budget_percent": 35},
                    "whatsapp": {"enabled": true, "budget_percent": 35}
                },
                "unified_messaging": {
                    "greeting": "Hi! How can we help?",
                    "offer": "Get 20% off your first order"
                }
            }
        
        Returns:
            ToolResult with cross-platform orchestration plan
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            strategy_name = arguments.get("strategy_name")
            
            if not all([ad_account_id, strategy_name]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id and strategy_name are required"}
                )
            
            logger.info(f"Orchestrating cross-platform strategy: {strategy_name}")
            
            total_budget = arguments.get("total_daily_budget", 10000)
            platforms = arguments.get("platforms", {})
            
            # Calculate budget allocation
            budget_allocation = {}
            for platform, config in platforms.items():
                if config.get("enabled"):
                    budget_allocation[platform] = {
                        "daily_budget": int(total_budget * (config.get("budget_percent", 0) / 100)),
                        "percent": config.get("budget_percent", 0)
                    }
            
            return ToolResult(
                ok=True,
                data={
                    "strategy_name": strategy_name,
                    "ad_account_id": ad_account_id,
                    "total_daily_budget": total_budget,
                    "budget_allocation": budget_allocation,
                    "platforms_active": len([p for p, c in platforms.items() if c.get("enabled")]),
                    "unified_messaging": arguments.get("unified_messaging", {}),
                    "orchestration_features": [
                        "Unified conversation inbox",
                        "Cross-platform lead deduplication",
                        "Channel preference learning",
                        "Automatic budget reallocation",
                        "Cross-channel attribution"
                    ],
                    "channel_strategy": {
                        "facebook_messenger": "Lead generation and customer support",
                        "instagram_direct": "Youth audience and visual products",
                        "whatsapp": "High-value leads and international markets"
                    },
                    "performance_optimization": {
                        "reallocate_budget": "Based on cost per qualified lead",
                        "pause_underperformers": "If CPL >2x account average",
                        "scale_winners": "Increase budget by 20% daily for top performers"
                    },
                    "monitoring_dashboard": {
                        "metrics_to_track": [
                            "Conversations by platform",
                            "Cost per conversation",
                            "Lead quality score",
                            "Conversion rate by platform",
                            "Channel preference patterns"
                        ],
                        "review_frequency": "Daily for first week, then weekly"
                    },
                    "success_criteria": {
                        "target_cpl": "$8-12",
                        "target_response_rate": ">70%",
                        "target_lead_quality": ">7/10"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("orchestrate_cross_platform_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"orchestrate_cross_platform_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def create_multi_advertiser_campaign(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Create multi-advertiser (partnership) campaign.
        
        Setup co-marketing campaigns with revenue/cost sharing.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "campaign_name": "Partnership Campaign",
                "partner_ad_account_id": "act_456",
                "cost_split_percent": 50,  # your share
                "revenue_split_percent": 50,
                "partnership_type": "co_marketing"  # or "influencer", "affiliate"
            }
        
        Returns:
            ToolResult with partnership campaign details
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            campaign_name = arguments.get("campaign_name")
            partner_account = arguments.get("partner_ad_account_id")
            
            if not all([ad_account_id, campaign_name, partner_account]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id, campaign_name, and partner_ad_account_id are required"}
                )
            
            logger.info(f"Creating multi-advertiser campaign: {campaign_name}")
            
            cost_split = arguments.get("cost_split_percent", 50)
            revenue_split = arguments.get("revenue_split_percent", 50)
            
            return ToolResult(
                ok=True,
                data={
                    "campaign_name": campaign_name,
                    "primary_account": ad_account_id,
                    "partner_account": partner_account,
                    "partnership_type": arguments.get("partnership_type", "co_marketing"),
                    "cost_sharing": {
                        "your_share": f"{cost_split}%",
                        "partner_share": f"{100 - cost_split}%",
                        "split_method": "proportional_to_results"
                    },
                    "revenue_sharing": {
                        "your_share": f"{revenue_split}%",
                        "partner_share": f"{100 - revenue_split}%"
                    },
                    "setup_requirements": [
                        "Both ad accounts must agree to partnership",
                        "Set up conversion tracking for attribution",
                        "Define clear revenue attribution rules",
                        "Establish reporting cadence",
                        "Sign partnership agreement"
                    ],
                    "tracking_infrastructure": {
                        "attribution_method": "last_click",
                        "reporting_frequency": "daily",
                        "reconciliation": "monthly",
                        "dispute_resolution": "defined in agreement"
                    },
                    "use_cases": [
                        "Brand + retailer partnerships",
                        "Influencer collaboration campaigns",
                        "Affiliate marketing",
                        "Co-branded product launches",
                        "Cross-promotion between complementary brands"
                    ],
                    "success_metrics": {
                        "combined_roas": "Target: 4.0+",
                        "incremental_reach": "Target: 50%+ new audience",
                        "cost_efficiency": "Target: 20%+ better than solo campaigns"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_multi_advertiser_campaign_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_multi_advertiser_campaign_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def compare_platform_performance(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Compare performance across Facebook, Instagram, WhatsApp, Messenger.
        
        Analyze which platforms work best for your business and audience.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "time_range": {"since": "2024-01-01", "until": "2024-01-31"},
                "comparison_metric": "cost_per_result"  # or "roas", "ctr"
            }
        
        Returns:
            ToolResult with platform performance comparison
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            time_range = arguments.get("time_range", {})
            
            if not ad_account_id:
                return ToolResult(ok=False, error={"message": "ad_account_id is required"})
            
            logger.info(f"Comparing platform performance for {ad_account_id}")
            
            # Simulate platform comparison data
            comparison = {
                "facebook": {
                    "spend": 5000.00,
                    "results": 250,
                    "cost_per_result": 20.00,
                    "roas": 4.5,
                    "ctr": 1.8,
                    "best_for": ["Age 35+", "B2B", "Long-form content"]
                },
                "instagram": {
                    "spend": 6000.00,
                    "results": 400,
                    "cost_per_result": 15.00,
                    "roas": 5.2,
                    "ctr": 2.4,
                    "best_for": ["Age 18-34", "Visual products", "E-commerce"]
                },
                "messenger": {
                    "spend": 3000.00,
                    "results": 180,
                    "cost_per_result": 16.67,
                    "roas": 4.8,
                    "ctr": 3.1,
                    "best_for": ["Lead generation", "Customer support", "Quick inquiries"]
                },
                "whatsapp": {
                    "spend": 2000.00,
                    "results": 100,
                    "cost_per_result": 20.00,
                    "roas": 6.5,
                    "ctr": 2.9,
                    "best_for": ["High-value leads", "International markets", "Consultations"]
                }
            }
            
            # Rank platforms
            metric = arguments.get("comparison_metric", "cost_per_result")
            ranked = sorted(
                comparison.items(),
                key=lambda x: x[1].get(metric, 0),
                reverse=(metric == "roas" or metric == "ctr")
            )
            
            return ToolResult(
                ok=True,
                data={
                    "ad_account_id": ad_account_id,
                    "time_range": time_range,
                    "comparison_metric": metric,
                    "platform_performance": comparison,
                    "ranking": [{"platform": p, "score": data.get(metric)} for p, data in ranked],
                    "winner": ranked[0][0],
                    "optimization_recommendations": [
                        f"Allocate more budget to {ranked[0][0]} (best {metric})",
                        f"Test different creative formats on {ranked[-1][0]}",
                        "Consider platform-specific creative strategies",
                        "Run A/B tests across platforms monthly"
                    ],
                    "audience_insights": {
                        "facebook": "Older, professional audience - good for B2B",
                        "instagram": "Younger, visual-focused - perfect for e-commerce",
                        "messenger": "Conversational buyers - ideal for complex products",
                        "whatsapp": "High-intent, international - best for premium products"
                    },
                    "budget_reallocation_suggestion": {
                        ranked[0][0]: "45%",
                        ranked[1][0]: "30%",
                        ranked[2][0]: "15%",
                        ranked[3][0]: "10%"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("compare_platform_performance_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"compare_platform_performance_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})


# Singleton pattern for engine access
_multi_platform_engine: Optional[MultiPlatformEngine] = None


def get_multi_platform_engine() -> MultiPlatformEngine:
    """Get the global MultiPlatformEngine instance"""
    global _multi_platform_engine
    if _multi_platform_engine is None:
        from .meta_client import get_client
        _multi_platform_engine = MultiPlatformEngine(get_client())
    return _multi_platform_engine

