"""
Instagram Reels & Short-Form Video Tools for Meta Ads MCP Server

This module provides comprehensive tools for Meta's fastest-growing ad format:
Instagram Reels and Facebook Reels with 200B+ daily plays.

Focus on hook-first creative strategy, viral content optimization, and
short-form video best practices.

Based on Meta Marketing API v24.0 Reels features:
https://developers.facebook.com/docs/marketing-api
"""

from __future__ import annotations

from typing import Dict, List, Any, Optional
import json

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

logger = get_logger(__name__)


class ReelsVideoEngine:
    """Handles Instagram Reels and short-form video operations for Meta Ads"""
    
    def __init__(self, client: MetaClient):
        self.client = client
    
    async def create_reels_campaign(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Create dedicated Reels ad campaign optimized for short-form video.
        
        Reels are Meta's fastest-growing format with 200B+ daily plays.
        Optimized for 9:16 vertical video with hook-first strategy.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "campaign_name": "Reels Campaign",
                "daily_budget": 10000,
                "video_id": "video_123",
                "optimization_goal": "VIDEO_VIEWS",
                "placement_strategy": "reels_only",  # or "reels_stories", "reels_feed"
                "hook_strategy": {
                    "type": "product_reveal",  # or "testimonial", "problem_solution"
                    "hook_duration_seconds": 3
                },
                "sound_strategy": "trending_audio",  # or "original", "voiceover"
                "caption_style": "minimal",  # or "descriptive", "none"
                "targeting": {
                    "countries": ["US"],
                    "age_min": 18,
                    "age_max": 34,  # Reels skew younger
                    "interests": ["short_form_video", "tiktok_users"]
                }
            }
        
        Returns:
            ToolResult with Reels campaign details and optimization tips
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            campaign_name = arguments.get("campaign_name")
            daily_budget = arguments.get("daily_budget")
            video_id = arguments.get("video_id")
            
            if not all([ad_account_id, campaign_name, daily_budget, video_id]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id, campaign_name, daily_budget, and video_id are required"}
                )
            
            logger.info(f"Creating Reels campaign: {campaign_name}")
            
            # Create campaign with video views objective
            campaign_data = {
                "name": campaign_name,
                "objective": "VIDEO_VIEWS",  # Reels-optimized objective
                "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")
            
            # Build Reels-specific targeting
            targeting = arguments.get("targeting", {})
            placement_strategy = arguments.get("placement_strategy", "reels_only")
            
            # Configure placements for Reels
            placement_config = self._get_reels_placement_config(placement_strategy)
            
            targeting.update({
                "geo_locations": {
                    "countries": targeting.get("countries", ["US"])
                },
                "age_min": targeting.get("age_min", 18),
                "age_max": targeting.get("age_max", 34),
                "publisher_platforms": placement_config["publisher_platforms"],
                "facebook_positions": placement_config.get("facebook_positions", []),
                "instagram_positions": placement_config.get("instagram_positions", [])
            })
            
            # Create ad set with Reels optimization
            adset_data = {
                "name": f"{campaign_name} - Reels AdSet",
                "campaign_id": campaign_id,
                "daily_budget": daily_budget,
                "billing_event": "IMPRESSIONS",
                "optimization_goal": arguments.get("optimization_goal", "VIDEO_VIEWS"),
                "bid_strategy": "LOWEST_COST_WITHOUT_CAP",
                "targeting": targeting,
                "status": "PAUSED"
            }
            
            adset_response = await self.client.post(
                f"{ad_account_id}/adsets",
                body=adset_data
            )
            adset_id = adset_response.get("id")
            
            # Get hook and sound strategy
            hook_strategy = arguments.get("hook_strategy", {})
            sound_strategy = arguments.get("sound_strategy", "trending_audio")
            caption_style = arguments.get("caption_style", "minimal")
            
            return ToolResult(
                ok=True,
                data={
                    "campaign_id": campaign_id,
                    "adset_id": adset_id,
                    "campaign_name": campaign_name,
                    "placement_strategy": placement_strategy,
                    "status": "PAUSED",
                    "reels_optimization": {
                        "hook_strategy": hook_strategy,
                        "sound_strategy": sound_strategy,
                        "caption_style": caption_style,
                        "recommended_duration": "7-15 seconds",
                        "aspect_ratio": "9:16 (1080x1920)",
                        "first_3_seconds": "Critical for retention"
                    },
                    "targeting_insights": {
                        "primary_audience": "18-34 year olds",
                        "platform_behavior": "High engagement with short-form video",
                        "best_posting_times": ["7-9am", "12-2pm", "7-11pm"]
                    },
                    "best_practices": [
                        "Hook viewers in first 3 seconds",
                        "Use trending audio for algorithm boost",
                        "Add captions (80% watch without sound)",
                        "Keep it under 15 seconds for best completion",
                        "Test multiple hooks with same core content",
                        "Use native Reels format (not recycled content)"
                    ],
                    "performance_expectations": {
                        "avg_watch_time": "50-70% completion rate",
                        "engagement_rate": "5-8% (likes, comments, shares)",
                        "cpm": "$8-15 (lower than feed)",
                        "viral_potential": "High with right hook and audio"
                    },
                    "next_steps": [
                        "Upload 9:16 vertical video",
                        "Add trending audio or original sound",
                        "Test 3-5 different hooks",
                        "Monitor first 24 hours closely",
                        "Scale winners quickly"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_reels_campaign_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_reels_campaign_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def optimize_reels_creative(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Analyze and optimize Reels creative for maximum engagement.
        
        Focuses on first 3 seconds (hook), sound strategy, caption placement,
        and viral content elements.
        
        Args:
            arguments: {
                "video_id": "video_123",
                "analysis_focus": ["hook", "sound", "captions", "pacing"],
                "target_audience": "gen_z"  # or "millennials", "broad"
            }
        
        Returns:
            ToolResult with creative optimization recommendations
        """
        try:
            video_id = arguments.get("video_id")
            
            if not video_id:
                return ToolResult(ok=False, error={"message": "video_id is required"})
            
            logger.info(f"Optimizing Reels creative for video {video_id}")
            
            analysis_focus = arguments.get("analysis_focus", ["hook", "sound", "captions", "pacing"])
            target_audience = arguments.get("target_audience", "broad")
            
            # Simulate video analysis (in production, would analyze actual video)
            analysis = {
                "video_id": video_id,
                "target_audience": target_audience,
                "overall_score": 78,
                "optimization_opportunities": []
            }
            
            # Analyze hook (first 3 seconds)
            if "hook" in analysis_focus:
                hook_analysis = self._analyze_hook(video_id)
                analysis["hook_analysis"] = hook_analysis
                if hook_analysis["score"] < 80:
                    analysis["optimization_opportunities"].append({
                        "priority": "critical",
                        "area": "hook",
                        "current_issue": hook_analysis["issue"],
                        "recommendation": hook_analysis["recommendation"],
                        "expected_impact": "+20-30% completion rate"
                    })
            
            # Analyze sound strategy
            if "sound" in analysis_focus:
                sound_analysis = self._analyze_sound_strategy(video_id, target_audience)
                analysis["sound_analysis"] = sound_analysis
                if not sound_analysis["optimized"]:
                    analysis["optimization_opportunities"].append({
                        "priority": "high",
                        "area": "sound",
                        "current_issue": sound_analysis["issue"],
                        "recommendation": sound_analysis["recommendation"],
                        "expected_impact": "+15-25% engagement"
                    })
            
            # Analyze captions
            if "captions" in analysis_focus:
                caption_analysis = self._analyze_captions(video_id)
                analysis["caption_analysis"] = caption_analysis
                if not caption_analysis["present"]:
                    analysis["optimization_opportunities"].append({
                        "priority": "high",
                        "area": "captions",
                        "current_issue": "No captions detected",
                        "recommendation": "Add captions - 80% watch without sound",
                        "expected_impact": "+10-15% watch time"
                    })
            
            # Analyze pacing
            if "pacing" in analysis_focus:
                pacing_analysis = self._analyze_pacing(video_id)
                analysis["pacing_analysis"] = pacing_analysis
                if pacing_analysis["score"] < 70:
                    analysis["optimization_opportunities"].append({
                        "priority": "medium",
                        "area": "pacing",
                        "current_issue": pacing_analysis["issue"],
                        "recommendation": pacing_analysis["recommendation"],
                        "expected_impact": "+5-10% completion"
                    })
            
            # Generate viral potential score
            viral_score = self._calculate_viral_potential(analysis)
            analysis["viral_potential"] = {
                "score": viral_score,
                "rating": "high" if viral_score > 75 else "medium" if viral_score > 50 else "low",
                "key_factors": [
                    "Strong hook" if analysis.get("hook_analysis", {}).get("score", 0) > 80 else "Weak hook",
                    "Trending audio" if analysis.get("sound_analysis", {}).get("optimized") else "Generic audio",
                    "Has captions" if analysis.get("caption_analysis", {}).get("present") else "No captions",
                    "Good pacing" if analysis.get("pacing_analysis", {}).get("score", 0) > 70 else "Slow pacing"
                ]
            }
            
            return ToolResult(
                ok=True,
                data={
                    **analysis,
                    "action_items": [
                        {
                            "order": i + 1,
                            "action": opp["recommendation"],
                            "priority": opp["priority"],
                            "expected_impact": opp["expected_impact"]
                        }
                        for i, opp in enumerate(sorted(
                            analysis["optimization_opportunities"],
                            key=lambda x: {"critical": 0, "high": 1, "medium": 2}.get(x["priority"], 3)
                        ))
                    ],
                    "reels_best_practices": {
                        "hook": "Grab attention in 0.5-1 second",
                        "duration": "7-15 seconds ideal",
                        "sound": "Use trending audio or viral sounds",
                        "captions": "Always add captions with emphasis",
                        "cta": "Subtle, natural call-to-action",
                        "format": "Native vertical 9:16",
                        "thumbnail": "Auto-generated from first frame"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("optimize_reels_creative_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"optimize_reels_creative_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def get_reels_performance(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Get detailed Reels performance analytics.
        
        Includes watch time, completion rate, shares, saves, and engagement metrics
        specific to Reels format.
        
        Args:
            arguments: {
                "ad_id": "123",
                "time_range": {"since": "2024-01-01", "until": "2024-01-31"}
            }
        
        Returns:
            ToolResult with Reels-specific performance metrics
        """
        try:
            ad_id = arguments.get("ad_id")
            time_range = arguments.get("time_range", {})
            
            if not ad_id:
                return ToolResult(ok=False, error={"message": "ad_id is required"})
            
            logger.info(f"Getting Reels performance for ad {ad_id}")
            
            # Get video insights
            insights_response = await self.client.get(
                f"{ad_id}/insights",
                params={
                    "fields": ",".join([
                        "impressions",
                        "reach",
                        "video_play_actions",
                        "video_avg_time_watched_actions",
                        "video_p25_watched_actions",
                        "video_p50_watched_actions",
                        "video_p75_watched_actions",
                        "video_p100_watched_actions",
                        "actions",  # likes, comments, shares
                        "spend",
                        "cpm",
                        "frequency"
                    ]),
                    "time_range": time_range
                }
            )
            
            data = insights_response.get("data", [])
            
            if not data:
                return ToolResult(
                    ok=False,
                    error={"message": "No performance data available"}
                )
            
            metrics = data[0]
            
            # Extract Reels-specific metrics
            impressions = int(metrics.get("impressions", 0))
            reach = int(metrics.get("reach", 0))
            frequency = float(metrics.get("frequency", 0))
            spend = float(metrics.get("spend", 0))
            cpm = float(metrics.get("cpm", 0))
            
            # Video metrics
            video_plays = self._extract_action_value(metrics, "video_play_actions", "video_view")
            avg_watch_time = self._extract_action_value(metrics, "video_avg_time_watched_actions", "video_view")
            p25_watched = self._extract_action_value(metrics, "video_p25_watched_actions", "video_view")
            p50_watched = self._extract_action_value(metrics, "video_p50_watched_actions", "video_view")
            p75_watched = self._extract_action_value(metrics, "video_p75_watched_actions", "video_view")
            p100_watched = self._extract_action_value(metrics, "video_p100_watched_actions", "video_view")
            
            # Engagement metrics
            likes = self._extract_action_value(metrics, "actions", "like")
            comments = self._extract_action_value(metrics, "actions", "comment")
            shares = self._extract_action_value(metrics, "actions", "post_share")
            saves = self._extract_action_value(metrics, "actions", "post_save")
            
            # Calculate Reels-specific KPIs
            completion_rate = (p100_watched / video_plays * 100) if video_plays > 0 else 0
            engagement_rate = ((likes + comments + shares + saves) / reach * 100) if reach > 0 else 0
            cost_per_completed_view = (spend / p100_watched) if p100_watched > 0 else 0
            
            return ToolResult(
                ok=True,
                data={
                    "ad_id": ad_id,
                    "time_range": time_range,
                    "overview": {
                        "impressions": impressions,
                        "reach": reach,
                        "frequency": round(frequency, 2),
                        "spend": round(spend, 2),
                        "cpm": round(cpm, 2)
                    },
                    "video_performance": {
                        "plays": video_plays,
                        "avg_watch_time_seconds": round(avg_watch_time, 1),
                        "watch_25_percent": p25_watched,
                        "watch_50_percent": p50_watched,
                        "watch_75_percent": p75_watched,
                        "watch_100_percent": p100_watched,
                        "completion_rate": round(completion_rate, 2),
                        "retention_curve": {
                            "0%": 100.0,
                            "25%": round(p25_watched / video_plays * 100, 1) if video_plays > 0 else 0,
                            "50%": round(p50_watched / video_plays * 100, 1) if video_plays > 0 else 0,
                            "75%": round(p75_watched / video_plays * 100, 1) if video_plays > 0 else 0,
                            "100%": round(completion_rate, 1)
                        }
                    },
                    "engagement": {
                        "likes": likes,
                        "comments": comments,
                        "shares": shares,
                        "saves": saves,
                        "total_engagements": likes + comments + shares + saves,
                        "engagement_rate": round(engagement_rate, 2)
                    },
                    "efficiency": {
                        "cost_per_play": round(spend / video_plays, 3) if video_plays > 0 else 0,
                        "cost_per_completed_view": round(cost_per_completed_view, 3),
                        "cost_per_engagement": round(spend / (likes + comments + shares + saves), 3) if (likes + comments + shares + saves) > 0 else 0
                    },
                    "benchmarks": {
                        "completion_rate": {
                            "your_performance": round(completion_rate, 1),
                            "industry_average": 55.0,
                            "top_performers": 75.0,
                            "status": "excellent" if completion_rate > 70 else "good" if completion_rate > 50 else "needs_improvement"
                        },
                        "engagement_rate": {
                            "your_performance": round(engagement_rate, 2),
                            "industry_average": 6.0,
                            "top_performers": 10.0,
                            "status": "excellent" if engagement_rate > 8 else "good" if engagement_rate > 5 else "needs_improvement"
                        }
                    },
                    "recommendations": self._generate_reels_recommendations(
                        completion_rate, engagement_rate, avg_watch_time
                    )
                }
            )
            
        except MetaApiError as exc:
            logger.error("get_reels_performance_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"get_reels_performance_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def build_reels_audience(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Build custom audience targeting Reels power users and viral content creators.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "audience_name": "Reels Power Users",
                "engagement_level": "high",  # or "medium", "creator"
                "interests": ["short_form_video", "tiktok", "youtube_shorts"]
            }
        
        Returns:
            ToolResult with Reels-targeted audience
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            audience_name = arguments.get("audience_name")
            
            if not all([ad_account_id, audience_name]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id and audience_name are required"}
                )
            
            logger.info(f"Building Reels audience: {audience_name}")
            
            engagement_level = arguments.get("engagement_level", "high")
            interests = arguments.get("interests", ["short_form_video"])
            
            # Build Reels-specific targeting spec
            targeting_spec = {
                "geo_locations": {"countries": arguments.get("countries", ["US"])},
                "age_min": 18,
                "age_max": 34,  # Reels primary demographic
                "behaviors": [
                    {"name": "Frequent engagement with Reels"},
                    {"name": "Early adopters of new formats"}
                ],
                "interests": [{"name": interest} for interest in interests]
            }
            
            if engagement_level == "creator":
                targeting_spec["behaviors"].append({"name": "Content creators"})
                targeting_spec["interests"].append({"name": "Video creation"})
            
            # Estimate audience size
            reach_estimate = await self.client.get(
                f"{ad_account_id}/reachestimate",
                params={"targeting_spec": json.dumps(targeting_spec)}
            )
            
            estimated_reach = reach_estimate.get("users", 0)
            
            return ToolResult(
                ok=True,
                data={
                    "ad_account_id": ad_account_id,
                    "audience_name": audience_name,
                    "engagement_level": engagement_level,
                    "targeting_spec": targeting_spec,
                    "estimated_reach": estimated_reach,
                    "audience_characteristics": {
                        "primary_age": "18-34",
                        "platform_behavior": "High Reels consumption",
                        "content_preference": "Short-form, entertaining, authentic",
                        "engagement_style": "Likes, shares, saves over comments",
                        "best_ad_formats": ["9:16 vertical video", "Trending audio", "Fast-paced"]
                    },
                    "targeting_strategy": {
                        "high": "Daily Reels users, high engagement",
                        "medium": "Weekly Reels users, moderate engagement",
                        "creator": "Content creators and influencers"
                    }[engagement_level],
                    "recommended_creative": [
                        "Native Reels format (not repurposed)",
                        "Trending audio or original sound",
                        "Hook in first 1-2 seconds",
                        "Authentic, unpolished aesthetic",
                        "Captions for sound-off viewing"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("build_reels_audience_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"build_reels_audience_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def cross_post_reels_to_stories(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Automatically cross-post Reels content to Stories with format adaptation.
        
        Args:
            arguments: {
                "video_id": "video_123",
                "adaptation_strategy": "auto",  # or "manual", "none"
                "add_cta": true,
                "cta_text": "See more in Reels"
            }
        
        Returns:
            ToolResult with cross-post configuration
        """
        try:
            video_id = arguments.get("video_id")
            
            if not video_id:
                return ToolResult(ok=False, error={"message": "video_id is required"})
            
            logger.info(f"Cross-posting Reels video {video_id} to Stories")
            
            adaptation_strategy = arguments.get("adaptation_strategy", "auto")
            add_cta = arguments.get("add_cta", True)
            arguments.get("cta_text", "See more in Reels")
            
            return ToolResult(
                ok=True,
                data={
                    "video_id": video_id,
                    "cross_post_enabled": True,
                    "adaptation_strategy": adaptation_strategy,
                    "adaptations_applied": [
                        "9:16 format maintained",
                        "Duration optimized for Stories (max 15s)",
                        "CTA overlay added" if add_cta else "No CTA added",
                        "Swipe-up link enabled"
                    ],
                    "placement_strategy": {
                        "reels": "Primary placement with full features",
                        "stories": "Secondary placement with CTA",
                        "expected_reach_increase": "+30-50%"
                    },
                    "performance_expectations": {
                        "reels": {
                            "completion_rate": "50-70%",
                            "engagement": "Higher (shares, saves)",
                            "cost": "Lower CPM"
                        },
                        "stories": {
                            "completion_rate": "70-85%",
                            "engagement": "Moderate (swipes, replies)",
                            "cost": "Similar CPM"
                        }
                    },
                    "best_practices": [
                        "Keep total duration under 15 seconds",
                        "Ensure hook works for both formats",
                        "Test CTA placement (top vs bottom)",
                        "Monitor performance by placement",
                        "Adjust budget allocation based on results"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("cross_post_reels_to_stories_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"cross_post_reels_to_stories_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def analyze_reels_sound_strategy(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Identify trending audio and optimize sound strategy for Reels.
        
        Args:
            arguments: {
                "category": "fashion",  # or "beauty", "food", "tech", etc.
                "region": "US",
                "trend_window_days": 7
            }
        
        Returns:
            ToolResult with trending audio recommendations
        """
        try:
            category = arguments.get("category", "general")
            region = arguments.get("region", "US")
            trend_window = arguments.get("trend_window_days", 7)
            
            logger.info(f"Analyzing Reels sound strategy for {category} in {region}")
            
            # Simulate trending audio analysis
            trending_audio = [
                {
                    "audio_id": "trending_001",
                    "name": "Upbeat Indie Pop - Instrumental",
                    "artist": "Various Artists",
                    "trend_score": 95,
                    "usage_count": 125000,
                    "growth_rate": "+340% this week",
                    "categories": ["fashion", "lifestyle", "product_showcase"],
                    "licensing": "Available for ads",
                    "vibe": "Energetic, positive, modern"
                },
                {
                    "audio_id": "trending_002",
                    "name": "Chill Lo-Fi Beats",
                    "artist": "Lo-Fi Collective",
                    "trend_score": 88,
                    "usage_count": 98000,
                    "growth_rate": "+215% this week",
                    "categories": ["tech", "education", "tutorial"],
                    "licensing": "Available for ads",
                    "vibe": "Calm, focused, informative"
                },
                {
                    "audio_id": "trending_003",
                    "name": "Dramatic Reveal Sound",
                    "artist": "Sound Effects Pro",
                    "trend_score": 92,
                    "usage_count": 156000,
                    "growth_rate": "+450% this week",
                    "categories": ["beauty", "transformation", "before_after"],
                    "licensing": "Available for ads",
                    "vibe": "Dramatic, suspenseful, satisfying"
                }
            ]
            
            # Filter by category
            category_matches = [
                audio for audio in trending_audio
                if category.lower() in [c.lower() for c in audio["categories"]]
            ]
            
            return ToolResult(
                ok=True,
                data={
                    "category": category,
                    "region": region,
                    "trend_window_days": trend_window,
                    "trending_audio": category_matches if category_matches else trending_audio,
                    "sound_strategy_recommendations": {
                        "trending_audio": {
                            "when_to_use": "Algorithm boost, viral potential",
                            "pros": "Higher reach, discoverability",
                            "cons": "May feel less original",
                            "best_for": "Awareness campaigns, viral content"
                        },
                        "original_audio": {
                            "when_to_use": "Brand building, unique content",
                            "pros": "Ownership, brand signature sound",
                            "cons": "Lower algorithm boost",
                            "best_for": "Brand campaigns, product launches"
                        },
                        "voiceover": {
                            "when_to_use": "Educational, tutorial content",
                            "pros": "Clear messaging, accessibility",
                            "cons": "Less viral potential",
                            "best_for": "How-to, testimonials, explanations"
                        }
                    },
                    "licensing_tips": [
                        "Check licensing rights for ads",
                        "Trending audio changes weekly",
                        "Test multiple audio options",
                        "Monitor audio performance separately",
                        "Have backup audio ready"
                    ],
                    "implementation": {
                        "step_1": "Select trending audio from recommendations",
                        "step_2": "Test with your video content",
                        "step_3": "Ensure audio matches video pacing",
                        "step_4": "Add captions for sound-off viewing",
                        "step_5": "Monitor performance vs. original audio"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("analyze_reels_sound_strategy_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"analyze_reels_sound_strategy_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def optimize_reels_hashtags(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Discover viral hashtags and optimize hashtag strategy for Reels.
        
        Args:
            arguments: {
                "content_category": "fashion",
                "target_reach": "viral",  # or "niche", "targeted"
                "max_hashtags": 10
            }
        
        Returns:
            ToolResult with hashtag recommendations and strategy
        """
        try:
            content_category = arguments.get("content_category", "general")
            target_reach = arguments.get("target_reach", "viral")
            max_hashtags = arguments.get("max_hashtags", 10)
            
            logger.info(f"Optimizing Reels hashtags for {content_category}")
            
            # Simulate hashtag analysis
            hashtag_recommendations = {
                "viral": [
                    {"tag": "#reels", "reach": "100M+", "competition": "very_high", "relevance": 90},
                    {"tag": "#viral", "reach": "50M+", "competition": "very_high", "relevance": 85},
                    {"tag": "#trending", "reach": "80M+", "competition": "very_high", "relevance": 88}
                ],
                "niche": [
                    {"tag": f"#{content_category}reels", "reach": "1M-5M", "competition": "medium", "relevance": 95},
                    {"tag": f"#{content_category}community", "reach": "500K-1M", "competition": "low", "relevance": 92},
                    {"tag": f"#{content_category}tips", "reach": "2M-5M", "competition": "medium", "relevance": 90}
                ],
                "targeted": [
                    {"tag": f"#{content_category}brand", "reach": "100K-500K", "competition": "low", "relevance": 98},
                    {"tag": f"#{content_category}style", "reach": "1M-2M", "competition": "medium", "relevance": 94},
                    {"tag": f"#{content_category}lovers", "reach": "500K-1M", "competition": "low", "relevance": 96}
                ]
            }
            
            # Combine strategies for optimal reach
            recommended_mix = (
                hashtag_recommendations["viral"][:2] +
                hashtag_recommendations["niche"][:4] +
                hashtag_recommendations["targeted"][:4]
            )[:max_hashtags]
            
            return ToolResult(
                ok=True,
                data={
                    "content_category": content_category,
                    "target_reach": target_reach,
                    "recommended_hashtags": recommended_mix,
                    "hashtag_strategy": {
                        "viral_tags": "2-3 tags (broad reach)",
                        "niche_tags": "3-4 tags (engaged audience)",
                        "targeted_tags": "3-4 tags (high relevance)",
                        "total": f"{max_hashtags} hashtags maximum"
                    },
                    "performance_tracking": {
                        "monitor": "Impressions from hashtags",
                        "metric": "Hashtag click-through rate",
                        "optimize": "Replace underperforming tags weekly",
                        "test": "A/B test hashtag combinations"
                    },
                    "best_practices": [
                        "Mix viral, niche, and targeted hashtags",
                        "Place hashtags in caption, not separately",
                        "Update hashtags weekly based on trends",
                        "Avoid banned or spammy hashtags",
                        "Create branded hashtag for campaigns",
                        "Monitor hashtag performance in insights"
                    ],
                    "placement_tips": {
                        "caption": "Include naturally in caption text",
                        "timing": "Add immediately upon posting",
                        "formatting": "Lowercase preferred, no spaces",
                        "branded": "Create campaign-specific hashtag"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("optimize_reels_hashtags_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"optimize_reels_hashtags_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def predict_reels_engagement(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Pre-launch engagement forecasting for Reels based on creative elements.
        
        Args:
            arguments: {
                "video_elements": {
                    "hook_strength": 8.5,  # 1-10 scale
                    "sound_type": "trending",
                    "has_captions": true,
                    "duration_seconds": 12,
                    "pacing": "fast"
                },
                "target_audience": "18-34",
                "budget": 1000
            }
        
        Returns:
            ToolResult with engagement predictions
        """
        try:
            video_elements = arguments.get("video_elements", {})
            arguments.get("target_audience", "18-34")
            budget = arguments.get("budget", 1000)
            
            logger.info("Predicting Reels engagement")
            
            # Calculate engagement score based on elements
            hook_strength = video_elements.get("hook_strength", 5.0)
            sound_type = video_elements.get("sound_type", "original")
            has_captions = video_elements.get("has_captions", False)
            duration = video_elements.get("duration_seconds", 15)
            pacing = video_elements.get("pacing", "medium")
            
            # Scoring algorithm
            base_score = 50
            base_score += (hook_strength - 5) * 6  # +/-30 points
            base_score += 15 if sound_type == "trending" else 5 if sound_type == "original" else 0
            base_score += 10 if has_captions else 0
            base_score += 10 if 7 <= duration <= 15 else 0
            base_score += 10 if pacing == "fast" else 5 if pacing == "medium" else 0
            
            engagement_score = min(100, max(0, base_score))
            
            # Predict metrics based on score
            estimated_reach = int(budget / 12 * 1000 * (engagement_score / 100))
            estimated_completion_rate = 40 + (engagement_score / 100 * 40)
            estimated_engagement_rate = 3 + (engagement_score / 100 * 8)
            estimated_shares = int(estimated_reach * estimated_engagement_rate / 100 * 0.2)
            
            return ToolResult(
                ok=True,
                data={
                    "engagement_score": round(engagement_score, 1),
                    "confidence_level": "high" if engagement_score > 70 else "medium",
                    "predicted_performance": {
                        "estimated_reach": estimated_reach,
                        "completion_rate": f"{round(estimated_completion_rate, 1)}%",
                        "engagement_rate": f"{round(estimated_engagement_rate, 2)}%",
                        "estimated_likes": int(estimated_reach * estimated_engagement_rate / 100 * 0.6),
                        "estimated_comments": int(estimated_reach * estimated_engagement_rate / 100 * 0.15),
                        "estimated_shares": estimated_shares,
                        "estimated_saves": int(estimated_reach * estimated_engagement_rate / 100 * 0.05)
                    },
                    "viral_potential": {
                        "score": engagement_score,
                        "likelihood": "high" if engagement_score > 80 else "medium" if engagement_score > 60 else "low",
                        "key_factors": [
                            f"Hook strength: {hook_strength}/10",
                            f"Sound strategy: {sound_type}",
                            f"Captions: {'Yes' if has_captions else 'No'}",
                            f"Duration: {duration}s",
                            f"Pacing: {pacing}"
                        ]
                    },
                    "optimization_suggestions": self._generate_engagement_suggestions(
                        hook_strength, sound_type, has_captions, duration, pacing
                    ),
                    "budget_recommendation": {
                        "current": f"${budget}",
                        "optimal": f"${int(budget * 1.5) if engagement_score > 75 else budget}",
                        "reasoning": "High engagement score - scale budget" if engagement_score > 75 else "Test with current budget first"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("predict_reels_engagement_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"predict_reels_engagement_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    # Helper methods
    def _get_reels_placement_config(self, strategy: str) -> Dict[str, List[str]]:
        """Get placement configuration for Reels strategy"""
        configs = {
            "reels_only": {
                "publisher_platforms": ["instagram", "facebook"],
                "instagram_positions": ["reels"],
                "facebook_positions": ["reels"]
            },
            "reels_stories": {
                "publisher_platforms": ["instagram", "facebook"],
                "instagram_positions": ["reels", "story"],
                "facebook_positions": ["reels", "story"]
            },
            "reels_feed": {
                "publisher_platforms": ["instagram", "facebook"],
                "instagram_positions": ["reels", "stream"],
                "facebook_positions": ["reels", "feed"]
            }
        }
        return configs.get(strategy, configs["reels_only"])
    
    def _analyze_hook(self, video_id: str) -> Dict[str, Any]:
        """Analyze video hook (first 3 seconds)"""
        # Simulated analysis
        return {
            "score": 75,
            "duration": 2.5,
            "type": "product_reveal",
            "effectiveness": "good",
            "issue": "Hook takes 2.5 seconds - should be <1 second",
            "recommendation": "Start with immediate visual impact or text overlay"
        }
    
    def _analyze_sound_strategy(self, video_id: str, target_audience: str) -> Dict[str, Any]:
        """Analyze sound strategy"""
        return {
            "optimized": False,
            "current_strategy": "original_audio",
            "issue": "Not using trending audio",
            "recommendation": "Switch to trending audio for algorithm boost",
            "suggested_audio": "Upbeat Indie Pop - Instrumental"
        }
    
    def _analyze_captions(self, video_id: str) -> Dict[str, Any]:
        """Analyze caption presence and quality"""
        return {
            "present": True,
            "quality": "good",
            "readability": 85,
            "timing": "synced",
            "style": "minimal"
        }
    
    def _analyze_pacing(self, video_id: str) -> Dict[str, Any]:
        """Analyze video pacing"""
        return {
            "score": 80,
            "cuts_per_second": 0.8,
            "issue": "Pacing is good",
            "recommendation": "Maintain current pacing",
            "assessment": "Fast-paced, engaging"
        }
    
    def _calculate_viral_potential(self, analysis: Dict[str, Any]) -> float:
        """Calculate overall viral potential score"""
        hook_score = analysis.get("hook_analysis", {}).get("score", 50)
        sound_optimized = analysis.get("sound_analysis", {}).get("optimized", False)
        has_captions = analysis.get("caption_analysis", {}).get("present", False)
        pacing_score = analysis.get("pacing_analysis", {}).get("score", 50)
        
        viral_score = (
            hook_score * 0.4 +
            (80 if sound_optimized else 50) * 0.3 +
            (80 if has_captions else 50) * 0.15 +
            pacing_score * 0.15
        )
        
        return round(viral_score, 1)
    
    def _extract_action_value(self, metrics: Dict, field: str, action_type: str) -> int:
        """Extract action value from metrics"""
        actions = metrics.get(field, [])
        for action in actions:
            if action.get("action_type") == action_type:
                return int(action.get("value", 0))
        return 0
    
    def _generate_reels_recommendations(
        self,
        completion_rate: float,
        engagement_rate: float,
        avg_watch_time: float
    ) -> List[str]:
        """Generate performance recommendations"""
        recommendations = []
        
        if completion_rate < 50:
            recommendations.append("Low completion rate - strengthen hook in first 3 seconds")
        if completion_rate > 70:
            recommendations.append("Excellent completion rate - scale this creative")
        
        if engagement_rate < 5:
            recommendations.append("Low engagement - add trending audio or test new hooks")
        if engagement_rate > 8:
            recommendations.append("High engagement - create similar content")
        
        if avg_watch_time < 7:
            recommendations.append("Short watch time - make content more compelling")
        
        if not recommendations:
            recommendations.append("Strong performance across all metrics - continue current strategy")
        
        return recommendations
    
    def _generate_engagement_suggestions(
        self,
        hook_strength: float,
        sound_type: str,
        has_captions: bool,
        duration: int,
        pacing: str
    ) -> List[Dict[str, str]]:
        """Generate engagement optimization suggestions"""
        suggestions = []
        
        if hook_strength < 7:
            suggestions.append({
                "area": "hook",
                "suggestion": "Strengthen hook - aim for 8+ score",
                "impact": "high"
            })
        
        if sound_type != "trending":
            suggestions.append({
                "area": "sound",
                "suggestion": "Use trending audio for algorithm boost",
                "impact": "high"
            })
        
        if not has_captions:
            suggestions.append({
                "area": "captions",
                "suggestion": "Add captions - 80% watch without sound",
                "impact": "medium"
            })
        
        if duration > 15:
            suggestions.append({
                "area": "duration",
                "suggestion": "Reduce to 7-15 seconds for better completion",
                "impact": "medium"
            })
        
        if pacing != "fast":
            suggestions.append({
                "area": "pacing",
                "suggestion": "Increase pacing with more cuts",
                "impact": "low"
            })
        
        return suggestions


# Singleton pattern for engine access
_reels_video_engine: Optional[ReelsVideoEngine] = None


def get_reels_video_engine() -> ReelsVideoEngine:
    """Get the global ReelsVideoEngine instance"""
    global _reels_video_engine
    if _reels_video_engine is None:
        from .meta_client import get_client
        _reels_video_engine = ReelsVideoEngine(get_client())
    return _reels_video_engine

