"""
Collaborative Ads & Influencer Marketing Tools for Meta Ads MCP Server

This module provides partnership ad capabilities where brands and creators
co-promote content, including branded content ads, creator partnerships,
UGC licensing, and authenticity analysis.

Based on Meta Marketing API v24.0 Branded Content and Partnership features:
https://developers.facebook.com/docs/marketing-api
https://developers.facebook.com/docs/instagram-api/guides/branded-content
"""

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 CollaborativeAdsEngine:
    """Handles collaborative ads and influencer marketing operations for Meta Ads"""
    
    def __init__(self, client: MetaClient):
        self.client = client
    
    async def create_branded_content_ad(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Create ads from creator organic posts with proper tagging.
        
        Amplify influencer content as ads while maintaining authenticity
        and proper disclosure.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "creator_post_id": "post_456",
                "campaign_name": "Influencer Partnership",
                "daily_budget": 5000,
                "targeting": {...},
                "partnership_type": "paid_partnership"  # or "branded_content"
            }
        
        Returns:
            ToolResult with branded content ad configuration
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            creator_post_id = arguments.get("creator_post_id")
            campaign_name = arguments.get("campaign_name")
            
            if not all([ad_account_id, creator_post_id, campaign_name]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id, creator_post_id, and campaign_name are required"}
                )
            
            logger.info(f"Creating branded content ad from post {creator_post_id}")
            
            # Create campaign
            campaign_data = {
                "name": campaign_name,
                "objective": "REACH",  # Common for branded content
                "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
            daily_budget = arguments.get("daily_budget", 5000)
            targeting = arguments.get("targeting", {})
            
            adset_data = {
                "name": f"{campaign_name} - Branded Content AdSet",
                "campaign_id": campaign_id,
                "daily_budget": daily_budget,
                "billing_event": "IMPRESSIONS",
                "optimization_goal": "REACH",
                "targeting": targeting,
                "status": "PAUSED"
            }
            
            adset_response = await self.client.post(
                f"{ad_account_id}/adsets",
                body=adset_data
            )
            adset_id = adset_response.get("id")
            
            partnership_type = arguments.get("partnership_type", "paid_partnership")
            
            return ToolResult(
                ok=True,
                data={
                    "campaign_id": campaign_id,
                    "adset_id": adset_id,
                    "creator_post_id": creator_post_id,
                    "partnership_type": partnership_type,
                    "status": "PAUSED",
                    "branded_content_features": {
                        "paid_partnership_label": True,
                        "creator_attribution": True,
                        "authenticity_maintained": True,
                        "engagement_preserved": True,
                        "creator_insights_shared": False  # Optional
                    },
                    "partnership_best_practices": {
                        "disclosure": [
                            "Always use Paid Partnership label",
                            "Ensure FTC compliance",
                            "Maintain transparency",
                            "Get creator approval before boosting"
                        ],
                        "content_selection": [
                            "Choose authentic, high-performing posts",
                            "Align with brand values",
                            "Ensure product placement is natural",
                            "Verify content rights and permissions"
                        ],
                        "optimization": [
                            "Test creator content vs brand content",
                            "Monitor engagement rates",
                            "Track brand lift metrics",
                            "Measure cost per engagement"
                        ]
                    },
                    "performance_expectations": {
                        "engagement_rate": "2-3x higher than brand content",
                        "trust_score": "40% higher with creator endorsement",
                        "cost_per_engagement": "30-50% lower",
                        "brand_recall": "+20-25% lift"
                    },
                    "creator_collaboration_tips": {
                        "communication": "Clear brief with creative freedom",
                        "approval_process": "Streamlined review and feedback",
                        "performance_sharing": "Provide insights to creator",
                        "long_term_relationship": "Build ongoing partnerships"
                    },
                    "legal_compliance": {
                        "ftc_guidelines": "Required disclosure for paid partnerships",
                        "platform_policies": "Follow Meta branded content policies",
                        "contracts": "Formal agreement with usage rights",
                        "approvals": "Creator must approve ad boosting"
                    },
                    "next_steps": [
                        "Get creator approval for ad use",
                        "Verify Paid Partnership label is active",
                        "Set appropriate budget and duration",
                        "Launch campaign",
                        "Share performance with creator",
                        "Consider extending successful partnerships"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_branded_content_ad_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_branded_content_ad_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def manage_creator_partnerships(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Invite creators, manage permissions, track performance.
        
        Args:
            arguments: {
                "page_id": "page_123",
                "creator_instagram_id": "ig_456",
                "partnership_type": "ongoing",  # or "campaign_specific", "ambassador"
                "permissions": ["post_content", "boost_posts", "share_insights"]
            }
        
        Returns:
            ToolResult with partnership management details
        """
        try:
            page_id = arguments.get("page_id")
            creator_instagram_id = arguments.get("creator_instagram_id")
            
            if not all([page_id, creator_instagram_id]):
                return ToolResult(
                    ok=False,
                    error={"message": "page_id and creator_instagram_id are required"}
                )
            
            logger.info(f"Managing creator partnership for {creator_instagram_id}")
            
            partnership_type = arguments.get("partnership_type", "campaign_specific")
            permissions = arguments.get("permissions", ["post_content", "boost_posts"])
            
            # Send partnership invitation
            
            return ToolResult(
                ok=True,
                data={
                    "page_id": page_id,
                    "creator_instagram_id": creator_instagram_id,
                    "partnership_type": partnership_type,
                    "partnership_status": "pending_acceptance",
                    "permissions_granted": permissions,
                    "partnership_types": {
                        "campaign_specific": {
                            "description": "Single campaign collaboration",
                            "duration": "1-3 months",
                            "commitment": "Low",
                            "best_for": "Testing creator fit, specific launches"
                        },
                        "ongoing": {
                            "description": "Regular content partnerships",
                            "duration": "6-12 months",
                            "commitment": "Medium",
                            "best_for": "Consistent brand presence, multiple campaigns"
                        },
                        "ambassador": {
                            "description": "Long-term brand representative",
                            "duration": "12+ months",
                            "commitment": "High",
                            "best_for": "Brand alignment, sustained influence"
                        }
                    },
                    "permission_levels": {
                        "post_content": "Creator can tag brand in posts",
                        "boost_posts": "Brand can promote creator content",
                        "share_insights": "Mutual performance data sharing",
                        "co_create": "Collaborative content development",
                        "exclusive_rights": "First rights to creator content"
                    },
                    "partnership_management": {
                        "onboarding": [
                            "Share brand guidelines and values",
                            "Provide product samples/access",
                            "Review content approval process",
                            "Set expectations and deliverables",
                            "Establish communication cadence"
                        ],
                        "ongoing_management": [
                            "Regular check-ins and feedback",
                            "Performance review meetings",
                            "Content collaboration sessions",
                            "Compensation and invoicing",
                            "Relationship nurturing"
                        ],
                        "performance_tracking": [
                            "Content engagement rates",
                            "Brand mention sentiment",
                            "Audience growth impact",
                            "Conversion attribution",
                            "ROI calculation"
                        ]
                    },
                    "compensation_models": {
                        "flat_fee": "Fixed payment per post/campaign",
                        "performance_based": "Payment tied to engagement/conversions",
                        "hybrid": "Base fee + performance bonuses",
                        "product_gifting": "Free products in exchange for content",
                        "affiliate": "Commission on sales driven",
                        "equity": "Company shares for long-term ambassadors"
                    },
                    "success_metrics": {
                        "reach": "Total unique audience reached",
                        "engagement": "Likes, comments, shares, saves",
                        "sentiment": "Positive vs negative mentions",
                        "conversions": "Tracked sales/leads",
                        "brand_lift": "Awareness and perception changes",
                        "roi": "Revenue vs partnership costs"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("manage_creator_partnerships_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"manage_creator_partnerships_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def license_ugc_content(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        License user-generated content for ads with rights management.
        
        Args:
            arguments: {
                "content_owner_id": "user_123",
                "content_post_id": "post_456",
                "license_type": "perpetual",  # or "term_limited", "campaign_specific"
                "usage_rights": ["ads", "organic", "website"],
                "compensation_offered": 500
            }
        
        Returns:
            ToolResult with UGC licensing details
        """
        try:
            content_owner_id = arguments.get("content_owner_id")
            content_post_id = arguments.get("content_post_id")
            
            if not all([content_owner_id, content_post_id]):
                return ToolResult(
                    ok=False,
                    error={"message": "content_owner_id and content_post_id are required"}
                )
            
            logger.info(f"Licensing UGC content from {content_owner_id}")
            
            license_type = arguments.get("license_type", "campaign_specific")
            usage_rights = arguments.get("usage_rights", ["ads"])
            compensation = arguments.get("compensation_offered", 0)
            
            return ToolResult(
                ok=True,
                data={
                    "content_owner_id": content_owner_id,
                    "content_post_id": content_post_id,
                    "license_type": license_type,
                    "usage_rights": usage_rights,
                    "compensation_offered": compensation,
                    "license_status": "pending_approval",
                    "ugc_licensing_process": {
                        "step_1_discovery": {
                            "action": "Identify high-quality UGC",
                            "tools": ["Social listening", "Hashtag monitoring", "Creator tags"],
                            "criteria": ["Brand alignment", "Quality", "Engagement", "Authenticity"]
                        },
                        "step_2_outreach": {
                            "action": "Contact content creator",
                            "method": ["DM", "Email", "Comment"],
                            "message": "Express interest, explain usage, offer compensation"
                        },
                        "step_3_negotiation": {
                            "action": "Agree on terms",
                            "components": ["Usage rights", "Duration", "Compensation", "Attribution"],
                            "documentation": "Formal license agreement"
                        },
                        "step_4_implementation": {
                            "action": "Use licensed content",
                            "applications": ["Ads", "Website", "Social posts", "Email"],
                            "tracking": "Performance monitoring and reporting"
                        }
                    },
                    "license_types": {
                        "perpetual": {
                            "description": "Unlimited duration usage",
                            "cost": "High (typically $1000-5000+)",
                            "best_for": "Evergreen content, key testimonials"
                        },
                        "term_limited": {
                            "description": "Fixed duration (e.g., 6-12 months)",
                            "cost": "Medium (typically $500-2000)",
                            "best_for": "Seasonal campaigns, product launches"
                        },
                        "campaign_specific": {
                            "description": "Single campaign use",
                            "cost": "Low (typically $200-1000)",
                            "best_for": "Testing UGC effectiveness, limited budgets"
                        }
                    },
                    "usage_rights_options": {
                        "paid_ads": "Meta/Instagram/Facebook paid advertising",
                        "organic_social": "Branded social media posts",
                        "website": "Product pages, testimonials, galleries",
                        "email_marketing": "Newsletters and promotional emails",
                        "retail": "In-store displays and materials",
                        "pr": "Press releases and media kits"
                    },
                    "compensation_guidelines": {
                        "micro_influencers": "$50-500 per content piece",
                        "mid_tier_creators": "$500-2000 per content piece",
                        "macro_influencers": "$2000-10000+ per content piece",
                        "non_monetary": "Product gifting, exclusive access, exposure",
                        "factors": ["Follower count", "Engagement rate", "Content quality", "Usage scope"]
                    },
                    "legal_requirements": {
                        "written_agreement": "Formal contract required",
                        "model_releases": "For identifiable people",
                        "property_releases": "For recognizable locations",
                        "trademark_usage": "Permission for brand mentions",
                        "attribution_rights": "How creator will be credited",
                        "termination_clause": "How either party can end agreement"
                    },
                    "ugc_performance_benefits": {
                        "authenticity": "79% of consumers say UGC highly impacts purchase decisions",
                        "trust": "90% trust UGC more than brand content",
                        "cost_efficiency": "50-80% lower production costs",
                        "engagement": "28% higher engagement than brand content",
                        "conversion": "161% higher conversion rates"
                    },
                    "best_practices": [
                        "Always get written permission",
                        "Be clear about usage and duration",
                        "Offer fair compensation",
                        "Maintain creator attribution",
                        "Report performance back to creator",
                        "Build long-term relationships",
                        "Respect creative integrity"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("license_ugc_content_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"license_ugc_content_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def track_influencer_performance(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        ROI by creator with audience overlap analysis.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "creator_ids": ["creator_1", "creator_2"],
                "time_range": {"since": "2024-01-01", "until": "2024-01-31"},
                "include_audience_overlap": true
            }
        
        Returns:
            ToolResult with creator performance comparison and ROI
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            creator_ids = arguments.get("creator_ids", [])
            
            if not all([ad_account_id, creator_ids]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id and creator_ids are required"}
                )
            
            logger.info(f"Tracking performance for {len(creator_ids)} creators")
            
            # Simulate creator performance data
            creator_performance = [
                {
                    "creator_id": "creator_1",
                    "creator_name": "@fashion_influencer",
                    "follower_count": 125000,
                    "engagement_rate": 4.2,
                    "partnership_performance": {
                        "posts_created": 8,
                        "total_reach": 450000,
                        "total_engagement": 18900,
                        "engagement_rate": 4.2,
                        "link_clicks": 5400,
                        "conversions": 189,
                        "revenue": 9450.00,
                        "cost": 4000.00,
                        "roi": 136.25
                    }
                },
                {
                    "creator_id": "creator_2",
                    "creator_name": "@lifestyle_blogger",
                    "follower_count": 89000,
                    "engagement_rate": 5.8,
                    "partnership_performance": {
                        "posts_created": 6,
                        "total_reach": 320000,
                        "total_engagement": 18560,
                        "engagement_rate": 5.8,
                        "link_clicks": 4800,
                        "conversions": 168,
                        "revenue": 8400.00,
                        "cost": 3000.00,
                        "roi": 180.00
                    }
                }
            ]
            
            # Calculate audience overlap if requested
            audience_overlap = None
            if arguments.get("include_audience_overlap", True):
                audience_overlap = {
                    "total_unique_reach": 698000,  # Not 770k due to overlap
                    "overlap_percentage": 9.4,
                    "overlapping_audience": 72000,
                    "overlap_impact": "Moderate - consider staggering posts or different messaging"
                }
            
            return ToolResult(
                ok=True,
                data={
                    "ad_account_id": ad_account_id,
                    "time_range": arguments.get("time_range", {}),
                    "creators_analyzed": len(creator_ids),
                    "creator_performance": creator_performance,
                    "comparative_analysis": {
                        "top_performer": {
                            "creator": "@lifestyle_blogger",
                            "metric": "ROI",
                            "value": "180%"
                        },
                        "highest_engagement": {
                            "creator": "@lifestyle_blogger",
                            "rate": "5.8%"
                        },
                        "most_conversions": {
                            "creator": "@fashion_influencer",
                            "conversions": 189
                        },
                        "best_value": {
                            "creator": "@lifestyle_blogger",
                            "cost_per_conversion": "$17.86"
                        }
                    },
                    "audience_overlap_analysis": audience_overlap,
                    "portfolio_recommendations": {
                        "continue": ["@lifestyle_blogger - highest ROI"],
                        "optimize": ["@fashion_influencer - good reach, improve conversion"],
                        "test_new": "Consider micro-influencers for cost efficiency",
                        "budget_allocation": {
                            "@lifestyle_blogger": "60% (high ROI)",
                            "@fashion_influencer": "40% (high reach)",
                            "new_creators": "Test with 10-20% of budget"
                        }
                    },
                    "optimization_strategies": {
                        "content_optimization": [
                            "Analyze top-performing post formats",
                            "Identify common elements in high-converting content",
                            "Share insights with creators for future posts",
                            "Test different CTAs and offers"
                        ],
                        "audience_targeting": [
                            "Use creator audiences for lookalikes",
                            "Target followers with similar interests",
                            "Exclude overlapping audiences to reduce waste",
                            "Test creator + brand audience combinations"
                        ],
                        "partnership_management": [
                            "Increase investment in top performers",
                            "Provide performance feedback to all creators",
                            "Co-create content strategy based on data",
                            "Consider long-term contracts for best creators"
                        ]
                    },
                    "roi_calculation_methodology": {
                        "revenue": "Tracked conversions × average order value",
                        "cost": "Creator fees + ad spend + management costs",
                        "roi_formula": "((Revenue - Cost) / Cost) × 100",
                        "attribution_window": "7-day click, 1-day view",
                        "considerations": ["Brand lift value", "Long-term customer value", "Organic reach value"]
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("track_influencer_performance_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"track_influencer_performance_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def configure_revenue_split(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Configure cost/revenue sharing between brand and creator.
        
        Args:
            arguments: {
                "partnership_id": "partnership_123",
                "split_model": "performance_based",  # or "fixed_split", "tiered"
                "brand_share_percent": 70,
                "creator_share_percent": 30,
                "minimum_guarantee": 1000,
                "performance_bonuses": [...]
            }
        
        Returns:
            ToolResult with revenue split configuration
        """
        try:
            partnership_id = arguments.get("partnership_id")
            split_model = arguments.get("split_model", "performance_based")
            
            if not partnership_id:
                return ToolResult(
                    ok=False,
                    error={"message": "partnership_id is required"}
                )
            
            logger.info(f"Configuring revenue split for partnership {partnership_id}")
            
            brand_share = arguments.get("brand_share_percent", 70)
            creator_share = arguments.get("creator_share_percent", 30)
            
            return ToolResult(
                ok=True,
                data={
                    "partnership_id": partnership_id,
                    "split_model": split_model,
                    "revenue_split": {
                        "brand_share_percent": brand_share,
                        "creator_share_percent": creator_share,
                        "minimum_guarantee": arguments.get("minimum_guarantee", 0),
                        "performance_bonuses": arguments.get("performance_bonuses", [])
                    },
                    "split_models": {
                        "fixed_split": {
                            "description": "Fixed percentage split of all revenue",
                            "example": "70/30 split regardless of performance",
                            "best_for": "Established partnerships, predictable outcomes",
                            "risk": "Low for both parties"
                        },
                        "performance_based": {
                            "description": "Variable split based on performance tiers",
                            "example": "Base 70/30, bonus 5% to creator at >$10k revenue",
                            "best_for": "Incentivizing high performance",
                            "risk": "Medium for brand, motivating for creator"
                        },
                        "tiered": {
                            "description": "Increasing creator share as revenue grows",
                            "example": "70/30 up to $10k, 60/40 from $10k-50k, 50/50 above $50k",
                            "best_for": "Scaling partnerships, reward growth",
                            "risk": "High for brand at scale, very motivating for creator"
                        },
                        "hybrid": {
                            "description": "Fixed base fee + performance incentives",
                            "example": "$2000 fixed + 20% of revenue above $10k",
                            "best_for": "Risk mitigation for both parties",
                            "risk": "Balanced risk/reward"
                        }
                    },
                    "revenue_calculation": {
                        "tracked_revenue": "Direct attributed sales from creator content",
                        "attribution_window": "7-day click, 1-day view (standard)",
                        "excluded": "Organic reach, brand lift (unless separately negotiated)",
                        "payment_timing": "Monthly, quarterly, or per-campaign",
                        "minimum_threshold": arguments.get("minimum_guarantee", 0)
                    },
                    "performance_bonus_structure": {
                        "revenue_tiers": [
                            {"threshold": 10000, "creator_bonus": 5},
                            {"threshold": 25000, "creator_bonus": 10},
                            {"threshold": 50000, "creator_bonus": 15}
                        ],
                        "engagement_bonuses": {
                            ">5%_engagement_rate": 500,
                            ">10000_saves": 300,
                            "viral_post_1M+_reach": 1000
                        },
                        "quality_bonuses": {
                            "best_performing_post": 250,
                            "highest_roas": 250
                        }
                    },
                    "contract_terms": {
                        "payment_schedule": "Monthly reconciliation",
                        "reporting": "Transparent performance dashboard",
                        "audit_rights": "Both parties can verify numbers",
                        "dispute_resolution": "Mediation clause",
                        "termination": "30-60 day notice period"
                    },
                    "tax_and_legal": {
                        "1099_required": "Yes, for US creators earning $600+",
                        "international_tax": "Varies by country, consult tax advisor",
                        "contract_review": "Legal review recommended",
                        "payment_processing": "Via platform or direct transfer"
                    },
                    "best_practices": [
                        "Start with simple fixed split",
                        "Add performance bonuses as relationship matures",
                        "Provide transparent reporting",
                        "Pay on time, every time",
                        "Review and adjust terms quarterly",
                        "Celebrate and reward top performance",
                        "Document everything formally"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("configure_revenue_split_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"configure_revenue_split_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def discover_creators_via_marketplace(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Discover and connect with Meta's Creator Marketplace.
        
        Args:
            arguments: {
                "brand_category": "fashion",
                "budget_range": {"min": 1000, "max": 10000},
                "audience_size": "micro",  # or "mid_tier", "macro", "mega"
                "target_demographics": {...}
            }
        
        Returns:
            ToolResult with creator recommendations
        """
        try:
            brand_category = arguments.get("brand_category", "general")
            
            logger.info(f"Discovering creators for category: {brand_category}")
            
            budget_range = arguments.get("budget_range", {"min": 1000, "max": 10000})
            audience_size = arguments.get("audience_size", "micro")
            
            # Simulate creator recommendations
            creators = [
                {
                    "creator_id": "creator_001",
                    "username": "@styleinfluencer",
                    "follower_count": 45000,
                    "engagement_rate": 6.2,
                    "category": "fashion",
                    "audience_demographics": {
                        "age_18_24": 35,
                        "age_25_34": 45,
                        "age_35_44": 15,
                        "female": 72,
                        "male": 28
                    },
                    "estimated_cost": 2500,
                    "content_style": "Lifestyle, outfit posts, styling tips",
                    "previous_brands": ["Fashion Nova", "Revolve", "H&M"],
                    "match_score": 92
                },
                {
                    "creator_id": "creator_002",
                    "username": "@fashiondaily",
                    "follower_count": 38000,
                    "engagement_rate": 7.5,
                    "category": "fashion",
                    "audience_demographics": {
                        "age_18_24": 40,
                        "age_25_34": 42,
                        "age_35_44": 13,
                        "female": 68,
                        "male": 32
                    },
                    "estimated_cost": 2000,
                    "content_style": "Product reviews, hauls, try-ons",
                    "previous_brands": ["ASOS", "Zara", "Urban Outfitters"],
                    "match_score": 88
                }
            ]
            
            return ToolResult(
                ok=True,
                data={
                    "brand_category": brand_category,
                    "budget_range": budget_range,
                    "audience_size": audience_size,
                    "creators_found": len(creators),
                    "recommended_creators": creators,
                    "creator_tiers": {
                        "nano": {
                            "follower_range": "1K-10K",
                            "typical_cost": "$100-500 per post",
                            "strengths": "High engagement, niche audiences, authentic",
                            "best_for": "Testing, community building, tight budgets"
                        },
                        "micro": {
                            "follower_range": "10K-100K",
                            "typical_cost": "$500-5000 per post",
                            "strengths": "Strong engagement, affordable, scalable",
                            "best_for": "Most brands, proven ROI, sustainable programs"
                        },
                        "mid_tier": {
                            "follower_range": "100K-500K",
                            "typical_cost": "$5000-25000 per post",
                            "strengths": "Broader reach, professional content",
                            "best_for": "Major launches, brand awareness, credibility"
                        },
                        "macro": {
                            "follower_range": "500K-1M+",
                            "typical_cost": "$25000-100000+ per post",
                            "strengths": "Massive reach, celebrity status",
                            "best_for": "Enterprise brands, mass awareness, big budgets"
                        }
                    },
                    "selection_criteria": {
                        "relevance": "Content aligns with brand values",
                        "engagement": "Active, authentic audience interaction",
                        "authenticity": "Genuine recommendations, not too many sponsors",
                        "audience_fit": "Demographics match target customer",
                        "content_quality": "Professional, on-brand aesthetic",
                        "professionalism": "Reliable, responsive, easy to work with"
                    },
                    "vetting_process": [
                        "Review content style and quality",
                        "Analyze engagement rate and patterns",
                        "Check previous brand partnerships",
                        "Verify audience authenticity (no bots)",
                        "Assess values and brand alignment",
                        "Contact references if available",
                        "Start with test campaign before commitment"
                    ],
                    "next_steps": [
                        "Shortlist 3-5 creators",
                        "Send partnership inquiries",
                        "Request media kits and rates",
                        "Negotiate terms and deliverables",
                        "Start with test campaign",
                        "Scale successful partnerships"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("discover_creators_via_marketplace_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"discover_creators_via_marketplace_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def analyze_authenticity_score(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Engagement quality and fake follower detection.
        
        Args:
            arguments: {
                "instagram_account_id": "ig_123"
            }
        
        Returns:
            ToolResult with authenticity analysis
        """
        try:
            instagram_account_id = arguments.get("instagram_account_id")
            
            if not instagram_account_id:
                return ToolResult(
                    ok=False,
                    error={"message": "instagram_account_id is required"}
                )
            
            logger.info(f"Analyzing authenticity for {instagram_account_id}")
            
            # Simulate authenticity analysis
            authenticity_report = {
                "instagram_account_id": instagram_account_id,
                "overall_authenticity_score": 87,
                "authenticity_rating": "High",
                "follower_quality": {
                    "total_followers": 45000,
                    "real_followers_percent": 92,
                    "suspicious_followers_percent": 8,
                    "bot_followers_estimated": 3600,
                    "quality_score": 85
                },
                "engagement_quality": {
                    "engagement_rate": 6.2,
                    "average_likes": 2790,
                    "average_comments": 89,
                    "average_shares": 45,
                    "engagement_authenticity": 90,
                    "comment_quality": "High - thoughtful responses",
                    "suspicious_activity": "Low - minimal spam/bot comments"
                },
                "growth_patterns": {
                    "monthly_follower_growth": 2.5,
                    "growth_pattern": "Steady and organic",
                    "sudden_spikes": "None detected",
                    "suspicious_drops": "None detected",
                    "growth_score": 95
                },
                "audience_demographics": {
                    "top_countries": {
                        "US": 45,
                        "UK": 15,
                        "Canada": 12,
                        "Australia": 10,
                        "other": 18
                    },
                    "gender_split": {
                        "female": 72,
                        "male": 28
                    },
                    "age_distribution": {
                        "18-24": 35,
                        "25-34": 45,
                        "35-44": 15,
                        "45+": 5
                    },
                    "demographic_authenticity": 88
                },
                "content_analysis": {
                    "post_frequency": "3-5 per week",
                    "content_variety": "Good mix of content types",
                    "sponsored_content_ratio": 15,  # 15% sponsored
                    "organic_engagement_vs_sponsored": "Consistent - no drop on sponsored posts",
                    "content_score": 90
                },
                "red_flags": {
                    "detected": [
                        "8% suspicious followers (acceptable range)"
                    ],
                    "not_detected": [
                        "No sudden follower spikes",
                        "No engagement pods detected",
                        "No fake giveaways",
                        "No comment pods",
                        "Reasonable sponsored post ratio"
                    ]
                },
                "partnership_risk_assessment": {
                    "overall_risk": "Low",
                    "recommendation": "Safe to partner - high authenticity",
                    "considerations": [
                        "87% authenticity score is above industry average (75%)",
                        "Engagement rate 6.2% is excellent for 45K followers",
                        "Organic growth pattern indicates real audience",
                        "Low suspicious activity",
                        "Reasonable sponsored content ratio"
                    ]
                },
                "industry_benchmarks": {
                    "your_score": 87,
                    "industry_average": 75,
                    "top_tier": 90,
                    "status": "Above average - recommended for partnership"
                },
                "improvement_suggestions": [
                    "Continue organic growth strategies",
                    "Remove identified fake followers (consider audit service)",
                    "Maintain current sponsored content ratio (under 20%)",
                    "Keep posting consistently",
                    "Continue engaging authentically with followers"
                ]
            }
            
            return ToolResult(ok=True, data=authenticity_report)
            
        except MetaApiError as exc:
            logger.error("analyze_authenticity_score_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"analyze_authenticity_score_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})


# Singleton pattern for engine access
_collaborative_ads_engine: Optional[CollaborativeAdsEngine] = None


def get_collaborative_ads_engine() -> CollaborativeAdsEngine:
    """Get the global CollaborativeAdsEngine instance"""
    global _collaborative_ads_engine
    if _collaborative_ads_engine is None:
        from .meta_client import get_client
        _collaborative_ads_engine = CollaborativeAdsEngine(get_client())
    return _collaborative_ads_engine

