"""
AR/VR & Immersive Ads Tools for Meta Ads MCP Server

This module provides Meta's future-forward advertising capabilities including
AR filters, virtual try-on, 3D product visualization, and Meta Horizon ads.

Based on Meta Marketing API v24.0 AR/VR features and Spark AR:
https://developers.facebook.com/docs/marketing-api
https://sparkar.facebook.com/ar-studio/
"""

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 ARVRAdsEngine:
    """Handles AR/VR and immersive ad operations for Meta Ads"""
    
    def __init__(self, client: MetaClient):
        self.client = client
    
    async def create_spark_ar_effect_ad(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Create ads featuring custom AR camera effects.
        
        Promote branded AR filters that users can try and share,
        driving organic reach and engagement through AR experiences.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "campaign_name": "AR Filter Campaign",
                "ar_effect_id": "effect_456",
                "daily_budget": 5000,
                "call_to_action": "TRY_IT",
                "targeting": {...}
            }
        
        Returns:
            ToolResult with AR effect ad configuration
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            campaign_name = arguments.get("campaign_name")
            ar_effect_id = arguments.get("ar_effect_id")
            
            if not all([ad_account_id, campaign_name, ar_effect_id]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id, campaign_name, and ar_effect_id are required"}
                )
            
            logger.info(f"Creating Spark AR effect ad: {campaign_name}")
            
            # Create campaign for AR effect
            campaign_data = {
                "name": campaign_name,
                "objective": "LINK_CLICKS",  # Drive to AR experience
                "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")
            
            return ToolResult(
                ok=True,
                data={
                    "campaign_id": campaign_id,
                    "ar_effect_id": ar_effect_id,
                    "campaign_name": campaign_name,
                    "status": "PAUSED",
                    "ar_effect_features": {
                        "try_it_button": True,
                        "share_to_story": True,
                        "save_to_camera": True,
                        "organic_distribution": True,
                        "effect_analytics": True
                    },
                    "ar_effect_types": {
                        "face_filters": {
                            "description": "Augment user's face with effects",
                            "examples": ["Makeup try-on", "Glasses/accessories", "Brand overlays"],
                            "engagement": "Very high - personal and shareable"
                        },
                        "world_effects": {
                            "description": "Place objects in real-world environment",
                            "examples": ["Furniture placement", "Product visualization", "Games"],
                            "engagement": "High - interactive and practical"
                        },
                        "target_tracking": {
                            "description": "Augment specific objects/images",
                            "examples": ["Product packaging activation", "Poster interactions"],
                            "engagement": "Medium - requires specific trigger"
                        },
                        "body_tracking": {
                            "description": "Full-body effects and try-ons",
                            "examples": ["Clothing try-on", "Full-body filters"],
                            "engagement": "High - immersive experience"
                        }
                    },
                    "spark_ar_development": {
                        "tool": "Spark AR Studio (free download)",
                        "platforms": "Facebook, Instagram, Messenger",
                        "requirements": [
                            "Mac or Windows computer",
                            "Spark AR Studio software",
                            "3D assets or images",
                            "Basic programming knowledge (optional)",
                            "Test device for preview"
                        ],
                        "process": [
                            "Design effect in Spark AR Studio",
                            "Test on mobile device",
                            "Submit for review",
                            "Publish to Effect Gallery",
                            "Create ads promoting effect"
                        ],
                        "approval_time": "2-7 days for review"
                    },
                    "performance_metrics": {
                        "effect_opens": "How many times effect was opened",
                        "effect_shares": "Shares to stories/feed",
                        "effect_saves": "Saves to camera effects",
                        "capture_rate": "% who create content with effect",
                        "avg_time_engaged": "Time spent using effect",
                        "organic_reach": "Reach from user-generated content"
                    },
                    "optimization_strategies": {
                        "effect_design": [
                            "Make it fun and shareable",
                            "Keep it simple and intuitive",
                            "Add brand elements subtly",
                            "Test on multiple faces/environments",
                            "Ensure good performance on all devices"
                        ],
                        "ad_creative": [
                            "Show effect in action",
                            "Use user-generated content",
                            "Highlight 'Try It' CTA",
                            "Demonstrate effect variety",
                            "Create intrigue and curiosity"
                        ],
                        "targeting": [
                            "Target early adopters and tech-savvy users",
                            "Lookalike audiences of AR users",
                            "Interest: AR, technology, innovation",
                            "Platform: Instagram and Facebook primarily"
                        ]
                    },
                    "success_examples": {
                        "beauty_brands": {
                            "use_case": "Virtual makeup try-on",
                            "results": "millions of effect opens, high brand recall"
                        },
                        "fashion_brands": {
                            "use_case": "Virtual clothing/accessories try-on",
                            "results": "increased purchase intent, reduced returns"
                        },
                        "entertainment": {
                            "use_case": "Movie/show themed filters",
                            "results": "viral UGC, massive organic reach"
                        }
                    },
                    "performance_expectations": {
                        "effect_open_rate": "5-15% of ad viewers",
                        "share_rate": "20-30% of effect users",
                        "organic_multiplier": "3-10x paid reach from UGC",
                        "cost_per_effect_open": "$0.50-2.00",
                        "viral_potential": "High with right effect design"
                    },
                    "next_steps": [
                        "Develop AR effect in Spark AR Studio",
                        "Submit effect for review",
                        "Create ad creative showcasing effect",
                        "Launch trial campaign",
                        "Monitor effect analytics",
                        "Encourage UGC with branded hashtag"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_spark_ar_effect_ad_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_spark_ar_effect_ad_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def create_virtual_tryon_campaign(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Beauty, fashion, accessories virtual fitting campaigns.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "campaign_name": "Virtual Try-On",
                "product_category": "beauty",  # or "eyewear", "fashion", "accessories"
                "product_ids": ["prod_1", "prod_2"],
                "daily_budget": 10000
            }
        
        Returns:
            ToolResult with virtual try-on campaign configuration
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            campaign_name = arguments.get("campaign_name")
            product_category = arguments.get("product_category", "beauty")
            
            if not all([ad_account_id, campaign_name]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id and campaign_name are required"}
                )
            
            logger.info(f"Creating virtual try-on campaign: {campaign_name}")
            
            product_ids = arguments.get("product_ids", [])
            
            return ToolResult(
                ok=True,
                data={
                    "ad_account_id": ad_account_id,
                    "campaign_name": campaign_name,
                    "product_category": product_category,
                    "products_count": len(product_ids),
                    "status": "draft",
                    "virtual_tryon_by_category": {
                        "beauty": {
                            "supported_products": ["Lipstick", "Eyeshadow", "Foundation", "Blush", "Eyeliner"],
                            "technology": "Face tracking + color mapping",
                            "accuracy": "95%+ realistic color match",
                            "conversion_lift": "+30-40% vs static ads",
                            "requirements": "Product SKUs with color codes"
                        },
                        "eyewear": {
                            "supported_products": ["Glasses", "Sunglasses"],
                            "technology": "Face tracking + 3D model overlay",
                            "accuracy": "90%+ size and fit accuracy",
                            "conversion_lift": "+25-35% vs static ads",
                            "requirements": "3D models or detailed specs"
                        },
                        "fashion": {
                            "supported_products": ["Hats", "Earrings", "Necklaces", "Watches"],
                            "technology": "Body/face tracking + AR overlay",
                            "accuracy": "85-90% realistic appearance",
                            "conversion_lift": "+20-30% vs static ads",
                            "requirements": "3D models or high-res images"
                        },
                        "accessories": {
                            "supported_products": ["Bags", "Shoes (limited)", "Watches"],
                            "technology": "Object detection + overlay",
                            "accuracy": "80-85% appearance match",
                            "conversion_lift": "+15-25% vs static ads",
                            "requirements": "Multiple angle photos or 3D models"
                        }
                    },
                    "implementation_requirements": {
                        "product_catalog": "Products must be in catalog with SKUs",
                        "3d_assets": "3D models for realistic rendering (recommended)",
                        "color_codes": "Accurate color specifications",
                        "ar_effect": "Custom Spark AR effect or Meta's try-on tools",
                        "mobile_optimization": "Optimized for mobile AR performance"
                    },
                    "consumer_benefits": {
                        "confidence": "Try before buying - reduce uncertainty",
                        "convenience": "At-home try-on anytime",
                        "variety": "Try multiple options quickly",
                        "shareability": "Share looks with friends for feedback",
                        "fun_factor": "Engaging, interactive experience"
                    },
                    "brand_benefits": {
                        "conversion_rate": "+20-40% increase",
                        "return_rate": "-20-30% decrease",
                        "engagement": "5-10x longer interaction time",
                        "basket_size": "+15-25% average order value",
                        "data_insights": "Color preferences, style insights"
                    },
                    "campaign_structure": {
                        "objective": "CONVERSIONS",
                        "placements": ["Instagram Feed", "Instagram Stories", "Facebook Feed"],
                        "creative": "Video showing try-on in action + 'Try It' CTA",
                        "landing": "AR try-on experience → product page",
                        "retargeting": "Engage users who tried products"
                    },
                    "optimization_tactics": {
                        "product_selection": [
                            "Start with bestsellers",
                            "Include variety of colors/styles",
                            "Test seasonal collections",
                            "Feature new launches"
                        ],
                        "creative_strategy": [
                            "Show diversity of models",
                            "Highlight ease of use",
                            "Demonstrate multiple products",
                            "User-generated content",
                            "Before/after comparisons"
                        ],
                        "funnel_optimization": [
                            "Smooth AR experience (fast loading)",
                            "Easy navigation between products",
                            "One-click purchase from AR",
                            "Social sharing integration",
                            "Save favorites feature"
                        ]
                    },
                    "performance_benchmarks": {
                        "ar_engagement_rate": "15-30% of ad viewers",
                        "tryon_to_purchase": "5-10% conversion",
                        "session_duration": "3-5 minutes average",
                        "products_tried_per_session": "4-8 products",
                        "cost_per_tryon": "$1-3",
                        "roas": "3-5x typical for established campaigns"
                    },
                    "technical_setup_guide": {
                        "step_1": "Create/obtain 3D models of products",
                        "step_2": "Develop or configure AR try-on effect",
                        "step_3": "Connect catalog to AR experience",
                        "step_4": "Test on multiple devices and face types",
                        "step_5": "Create promotional ads",
                        "step_6": "Launch and monitor performance"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_virtual_tryon_campaign_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_virtual_tryon_campaign_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def create_3d_product_showcase(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Upload and display 3D models in ads.
        
        Args:
            arguments: {
                "product_id": "prod_123",
                "model_3d_url": "https://example.com/model.glb",
                "enable_ar_view": true,
                "background_color": "#FFFFFF"
            }
        
        Returns:
            ToolResult with 3D product showcase configuration
        """
        try:
            product_id = arguments.get("product_id")
            model_3d_url = arguments.get("model_3d_url")
            
            if not all([product_id, model_3d_url]):
                return ToolResult(
                    ok=False,
                    error={"message": "product_id and model_3d_url are required"}
                )
            
            logger.info(f"Creating 3D product showcase for {product_id}")
            
            enable_ar = arguments.get("enable_ar_view", True)
            
            return ToolResult(
                ok=True,
                data={
                    "product_id": product_id,
                    "model_3d_url": model_3d_url,
                    "ar_enabled": enable_ar,
                    "background_color": arguments.get("background_color", "#FFFFFF"),
                    "status": "ready",
                    "3d_model_specifications": {
                        "format": "glTF 2.0 (.glb or .gltf)",
                        "max_file_size": "10 MB recommended, 50 MB max",
                        "polygon_count": "Under 100K triangles recommended",
                        "textures": "PBR materials, 2K resolution max",
                        "animations": "Supported but optional",
                        "compression": "Draco compression recommended"
                    },
                    "interactive_features": {
                        "rotation": "360° product rotation",
                        "zoom": "Pinch to zoom in/out",
                        "pan": "Drag to adjust view angle",
                        "ar_placement": "Place in real environment (if enabled)",
                        "annotations": "Add product feature callouts",
                        "configurator": "Change colors/materials (advanced)"
                    },
                    "creation_methods": {
                        "photogrammetry": {
                            "description": "Capture from multiple photos",
                            "tools": ["RealityCapture", "Polycam", "Meshroom"],
                            "cost": "Low - free to $50",
                            "quality": "Good for real products",
                            "time": "1-2 hours"
                        },
                        "3d_modeling": {
                            "description": "Create from scratch",
                            "tools": ["Blender", "Maya", "3ds Max"],
                            "cost": "Medium - software + time",
                            "quality": "Excellent, full control",
                            "time": "4-40 hours depending on complexity"
                        },
                        "ai_generation": {
                            "description": "AI-powered 3D from images",
                            "tools": ["Luma AI", "Kaedim"],
                            "cost": "Medium - $10-100 per model",
                            "quality": "Good, fast turnaround",
                            "time": "Minutes to hours"
                        },
                        "outsourcing": {
                            "description": "Hire 3D artist",
                            "platforms": ["Fiverr", "Upwork", "CGTrader"],
                            "cost": "High - $50-500+ per model",
                            "quality": "Professional",
                            "time": "1-7 days"
                        }
                    },
                    "optimization_best_practices": {
                        "performance": [
                            "Keep polygon count under 100K",
                            "Use power-of-2 texture sizes (1024x1024, 2048x2048)",
                            "Apply Draco compression",
                            "Remove unnecessary faces/vertices",
                            "Bake textures when possible"
                        ],
                        "visual_quality": [
                            "Use PBR materials for realism",
                            "Include roughness/metallic maps",
                            "Proper UV unwrapping",
                            "Consistent scale (real-world units)",
                            "Test lighting in viewer"
                        ],
                        "ar_considerations": [
                            "Ensure correct scale for AR",
                            "Add shadow plane for realism",
                            "Test on actual device",
                            "Consider lighting conditions",
                            "Optimize for mobile GPUs"
                        ]
                    },
                    "ad_placement_options": {
                        "facebook_feed": "3D viewer in feed, swipe to rotate",
                        "instagram_feed": "3D post with AR CTA",
                        "stories": "Tap to view in AR",
                        "facebook_marketplace": "3D product listings",
                        "collection_ads": "3D product grid"
                    },
                    "performance_impact": {
                        "engagement_time": "+60-80% vs 2D images",
                        "product_understanding": "+40% better comprehension",
                        "purchase_confidence": "+35% increase",
                        "return_rate": "-25% fewer returns",
                        "conversion_rate": "+20-30% lift"
                    },
                    "testing_checklist": [
                        "Model loads in under 3 seconds on 4G",
                        "Smooth rotation on mid-range devices",
                        "Correct scale in AR view",
                        "Textures render properly",
                        "No visual glitches or gaps",
                        "Works on iOS and Android",
                        "File size optimized"
                    ],
                    "next_steps": [
                        "Create or acquire 3D model",
                        "Optimize for web/mobile",
                        "Upload to Meta",
                        "Test in ad preview",
                        "Create ad campaign",
                        "Monitor engagement metrics"
                    ]
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_3d_product_showcase_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_3d_product_showcase_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def create_ar_shopping_experience(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Place products in user's environment via AR.
        
        Args:
            arguments: {
                "product_id": "prod_123",
                "product_category": "furniture",  # or "decor", "appliances"
                "enable_room_scan": true,
                "enable_measurement": true
            }
        
        Returns:
            ToolResult with AR shopping experience configuration
        """
        try:
            product_id = arguments.get("product_id")
            product_category = arguments.get("product_category", "furniture")
            
            if not product_id:
                return ToolResult(
                    ok=False,
                    error={"message": "product_id is required"}
                )
            
            logger.info(f"Creating AR shopping experience for {product_id}")
            
            return ToolResult(
                ok=True,
                data={
                    "product_id": product_id,
                    "product_category": product_category,
                    "ar_features": {
                        "room_placement": True,
                        "scale_accuracy": True,
                        "room_scan": arguments.get("enable_room_scan", True),
                        "measurement_tools": arguments.get("enable_measurement", True),
                        "lighting_adaptation": True,
                        "shadow_rendering": True
                    },
                    "use_cases_by_category": {
                        "furniture": {
                            "products": ["Sofas", "Tables", "Chairs", "Beds", "Cabinets"],
                            "ar_value": "Critical - see fit and scale in space",
                            "return_reduction": "60-70%",
                            "conversion_lift": "+40-50%"
                        },
                        "home_decor": {
                            "products": ["Art", "Mirrors", "Rugs", "Lamps", "Plants"],
                            "ar_value": "High - visualize style and placement",
                            "return_reduction": "40-50%",
                            "conversion_lift": "+30-40%"
                        },
                        "appliances": {
                            "products": ["Refrigerators", "Ovens", "Washers"],
                            "ar_value": "High - confirm space fit",
                            "return_reduction": "50-60%",
                            "conversion_lift": "+25-35%"
                        },
                        "electronics": {
                            "products": ["TVs", "Speakers", "Computers"],
                            "ar_value": "Medium - visualize size",
                            "return_reduction": "30-40%",
                            "conversion_lift": "+20-30%"
                        }
                    },
                    "ar_placement_features": {
                        "surface_detection": "Automatically find floors/walls/tables",
                        "realistic_shadows": "Dynamic shadows based on room lighting",
                        "scale_adjustment": "Pinch to resize for perfect fit",
                        "rotation": "Rotate 360° to try different orientations",
                        "multiple_items": "Place multiple products together",
                        "measurement_overlay": "Show dimensions in real-world units",
                        "photo_capture": "Save AR preview to camera roll"
                    },
                    "technical_requirements": {
                        "device_compatibility": "ARCore (Android) / ARKit (iOS)",
                        "os_requirements": "iOS 13+ / Android 8.0+",
                        "3d_model": "GLB format with accurate scale",
                        "model_optimization": "Under 50MB, optimized for mobile",
                        "testing": "Test in various room conditions"
                    },
                    "consumer_workflow": {
                        "step_1": "Tap 'View in Your Space' from ad",
                        "step_2": "Grant camera access",
                        "step_3": "Point camera at floor/wall",
                        "step_4": "Place product in scene",
                        "step_5": "Adjust position, rotation, scale",
                        "step_6": "Take photo or proceed to purchase",
                        "avg_duration": "2-4 minutes"
                    },
                    "business_impact": {
                        "purchase_confidence": "+45% - see before buying",
                        "return_rate_reduction": "50-70% - proper fit verification",
                        "session_value": "+35% - visualize more products",
                        "cart_abandonment": "-30% - reduced uncertainty",
                        "customer_satisfaction": "+40% - meets expectations"
                    },
                    "optimization_strategies": {
                        "product_selection": [
                            "Start with high-return-rate products",
                            "Focus on size/fit-critical items",
                            "Include bestsellers first",
                            "Test seasonal collections"
                        ],
                        "creative_promotion": [
                            "Show AR in action in ads",
                            "Highlight 'See in Your Space' feature",
                            "Use customer testimonials",
                            "Compare with/without AR"
                        ],
                        "experience_design": [
                            "Fast loading times (<3 seconds)",
                            "Intuitive controls",
                            "Clear instructions",
                            "Easy sharing",
                            "Seamless checkout"
                        ]
                    },
                    "competitive_advantages": {
                        "vs_static_images": "45% better purchase confidence",
                        "vs_showroom_visit": "Convenience + unlimited options",
                        "vs_competitors_without_ar": "Significant differentiation",
                        "first_mover": "Early adoption builds competitive moat"
                    },
                    "implementation_roadmap": {
                        "week_1_2": "Create 3D models of top 10 products",
                        "week_3": "Develop AR experience and test",
                        "week_4": "Create promotional campaigns",
                        "week_5": "Soft launch to segment",
                        "week_6_8": "Full launch and optimization",
                        "ongoing": "Expand product catalog"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_ar_shopping_experience_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_ar_shopping_experience_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def create_meta_horizon_ad(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Future-ready: Ads within Meta's VR platform.
        
        Args:
            arguments: {
                "ad_account_id": "act_123",
                "campaign_name": "Meta Horizon Campaign",
                "vr_experience_url": "https://example.com/vr",
                "targeting": {...}
            }
        
        Returns:
            ToolResult with Meta Horizon ad configuration (future-ready)
        """
        try:
            ad_account_id = arguments.get("ad_account_id")
            campaign_name = arguments.get("campaign_name")
            
            if not all([ad_account_id, campaign_name]):
                return ToolResult(
                    ok=False,
                    error={"message": "ad_account_id and campaign_name are required"}
                )
            
            logger.info(f"Creating Meta Horizon ad (future-ready): {campaign_name}")
            
            return ToolResult(
                ok=True,
                data={
                    "ad_account_id": ad_account_id,
                    "campaign_name": campaign_name,
                    "vr_experience_url": arguments.get("vr_experience_url", ""),
                    "status": "future_platform",
                    "platform_note": "Meta Horizon ads are in early development - this tool is future-ready",
                    "meta_horizon_overview": {
                        "description": "Meta's VR social platform (formerly Horizon Worlds)",
                        "availability": "Currently Oculus Quest 2/Pro",
                        "user_base": "Growing rapidly - millions of monthly users",
                        "advertising_status": "Beta/limited availability",
                        "full_launch_expected": "2024-2025"
                    },
                    "vr_ad_formats": {
                        "immersive_billboards": {
                            "description": "3D billboards in virtual worlds",
                            "placement": "High-traffic virtual areas",
                            "interaction": "Clickable portals to experiences",
                            "best_for": "Brand awareness, event promotion"
                        },
                        "sponsored_experiences": {
                            "description": "Branded virtual experiences/games",
                            "placement": "Featured in Horizon Worlds hub",
                            "interaction": "Full immersive brand experience",
                            "best_for": "Deep engagement, product launches"
                        },
                        "avatar_items": {
                            "description": "Branded wearables for avatars",
                            "placement": "Avatar shop",
                            "interaction": "Try-on and purchase",
                            "best_for": "Fashion, gaming, entertainment"
                        },
                        "virtual_stores": {
                            "description": "3D storefronts in the metaverse",
                            "placement": "Virtual shopping districts",
                            "interaction": "Browse and purchase real products",
                            "best_for": "Retail, e-commerce"
                        }
                    },
                    "targeting_capabilities": {
                        "demographics": "Age, location (limited)",
                        "interests": "Gaming, VR enthusiasts, early adopters",
                        "behaviors": "VR usage frequency, worlds visited",
                        "device": "Quest 2, Quest Pro",
                        "lookalike": "Similar to VR users (future)"
                    },
                    "creative_requirements": {
                        "3d_assets": "Full 3D models and environments",
                        "vr_optimization": "Optimized for VR performance (90fps)",
                        "interaction_design": "Controller-based or hand tracking",
                        "spatial_audio": "3D audio for immersion",
                        "accessibility": "Comfort settings, teleport options"
                    },
                    "measurement_metrics": {
                        "impressions": "Times ad was viewed in VR",
                        "engagement_time": "Time spent interacting",
                        "world_visits": "Visits to branded experiences",
                        "avatar_item_adoptions": "Wearables equipped",
                        "conversions": "Real-world actions (future)"
                    },
                    "early_adopter_advantages": {
                        "first_mover": "Establish presence before saturation",
                        "learning_curve": "Master VR advertising early",
                        "brand_perception": "Seen as innovative/forward-thinking",
                        "partnerships": "Early access to Meta features",
                        "lower_competition": "Less crowded ad space initially"
                    },
                    "preparation_steps": {
                        "now": [
                            "Experiment with Horizon Worlds",
                            "Build 3D asset library",
                            "Develop VR strategy",
                            "Train team on VR concepts",
                            "Join Meta for Business VR programs"
                        ],
                        "when_available": [
                            "Launch pilot VR campaigns",
                            "Create branded VR experiences",
                            "Test different ad formats",
                            "Measure and optimize",
                            "Scale successful initiatives"
                        ]
                    },
                    "investment_considerations": {
                        "timeline": "2-5 year horizon for mainstream adoption",
                        "risk": "Platform still evolving",
                        "reward": "First-mover advantage in metaverse",
                        "budget": "Higher production costs for VR content",
                        "learning": "New skillsets required"
                    },
                    "future_vision": {
                        "commerce": "Virtual and physical product sales",
                        "events": "Concerts, conferences, experiences",
                        "social": "Virtual hangouts with brand integration",
                        "gaming": "Branded games and competitions",
                        "education": "Training and educational experiences"
                    }
                }
            )
            
        except MetaApiError as exc:
            logger.error("create_meta_horizon_ad_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"create_meta_horizon_ad_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})
    
    async def get_ar_performance_analytics(
        self, 
        arguments: Dict[str, Any]
    ) -> ToolResult:
        """
        Engagement time, interaction rate, conversion tracking for AR ads.
        
        Args:
            arguments: {
                "ar_effect_id": "effect_123",
                "time_range": {"since": "2024-01-01", "until": "2024-01-31"}
            }
        
        Returns:
            ToolResult with AR performance metrics
        """
        try:
            ar_effect_id = arguments.get("ar_effect_id")
            
            if not ar_effect_id:
                return ToolResult(
                    ok=False,
                    error={"message": "ar_effect_id is required"}
                )
            
            logger.info(f"Getting AR performance analytics for {ar_effect_id}")
            
            # Simulate AR analytics
            analytics = {
                "ar_effect_id": ar_effect_id,
                "time_range": arguments.get("time_range", {}),
                "overview": {
                    "total_impressions": 250000,
                    "effect_opens": 25000,
                    "open_rate": 10.0,
                    "total_captures": 7500,
                    "capture_rate": 30.0,
                    "total_shares": 3750,
                    "share_rate": 15.0
                },
                "engagement_metrics": {
                    "avg_session_duration": 45.5,  # seconds
                    "median_session_duration": 35.0,
                    "total_engagement_time": 315.97,  # hours
                    "return_rate": 22.0,  # % who used effect multiple times
                    "avg_uses_per_user": 1.8
                },
                "interaction_breakdown": {
                    "just_viewed": {
                        "count": 13750,
                        "percentage": 55.0,
                        "avg_duration": 15.0
                    },
                    "created_content": {
                        "count": 7500,
                        "percentage": 30.0,
                        "avg_duration": 60.0
                    },
                    "shared_to_story": {
                        "count": 3000,
                        "percentage": 12.0,
                        "organic_reach": 180000
                    },
                    "shared_to_feed": {
                        "count": 750,
                        "percentage": 3.0,
                        "organic_reach": 90000
                    }
                },
                "organic_amplification": {
                    "paid_reach": 250000,
                    "organic_reach_from_ugc": 270000,
                    "amplification_factor": 1.08,
                    "total_reach": 520000,
                    "earned_media_value": 13500.00  # Estimated value of organic reach
                },
                "conversion_funnel": {
                    "ad_impressions": 250000,
                    "effect_opens": 25000,
                    "content_creates": 7500,
                    "shares": 3750,
                    "website_clicks": 5000,
                    "conversions": 250,
                    "revenue": 12500.00
                },
                "conversion_rates": {
                    "impression_to_open": 10.0,
                    "open_to_create": 30.0,
                    "create_to_share": 50.0,
                    "open_to_convert": 1.0,
                    "overall_conversion": 0.1
                },
                "cost_metrics": {
                    "total_spend": 5000.00,
                    "cpm": 20.00,
                    "cost_per_effect_open": 0.20,
                    "cost_per_capture": 0.67,
                    "cost_per_share": 1.33,
                    "cost_per_conversion": 20.00,
                    "roas": 2.5
                },
                "demographics": {
                    "age": {
                        "13-17": 15,
                        "18-24": 45,
                        "25-34": 30,
                        "35-44": 8,
                        "45+": 2
                    },
                    "gender": {
                        "female": 62,
                        "male": 38
                    },
                    "top_locations": [
                        {"country": "US", "percentage": 40},
                        {"country": "UK", "percentage": 15},
                        {"country": "Canada", "percentage": 12}
                    ]
                },
                "device_breakdown": {
                    "iPhone": 55,
                    "Android": 45
                },
                "platform_performance": {
                    "Instagram": {
                        "effect_opens": 18750,
                        "percentage": 75,
                        "engagement_rate": 32.0
                    },
                    "Facebook": {
                        "effect_opens": 6250,
                        "percentage": 25,
                        "engagement_rate": 25.0
                    }
                },
                "time_analysis": {
                    "peak_days": ["Saturday", "Sunday", "Friday"],
                    "peak_hours": ["7-9pm", "12-2pm", "8-10am"],
                    "lowest_engagement": ["Monday morning", "Tuesday"]
                },
                "benchmarks": {
                    "your_performance": {
                        "open_rate": 10.0,
                        "capture_rate": 30.0,
                        "share_rate": 15.0
                    },
                    "industry_average": {
                        "open_rate": 8.0,
                        "capture_rate": 25.0,
                        "share_rate": 10.0
                    },
                    "top_performers": {
                        "open_rate": 15.0,
                        "capture_rate": 40.0,
                        "share_rate": 20.0
                    },
                    "status": "Above average - good performance"
                },
                "optimization_recommendations": [
                    {
                        "priority": "high",
                        "area": "Open rate",
                        "current": "10%",
                        "target": "15%",
                        "action": "Improve ad creative to better showcase effect",
                        "expected_impact": "+5% open rate"
                    },
                    {
                        "priority": "medium",
                        "area": "Share rate",
                        "current": "15%",
                        "target": "20%",
                        "action": "Add more shareable elements, encourage UGC",
                        "expected_impact": "+5% share rate"
                    },
                    {
                        "priority": "medium",
                        "area": "Conversion rate",
                        "current": "0.1%",
                        "target": "0.15%",
                        "action": "Improve effect-to-purchase pathway",
                        "expected_impact": "+50% more conversions"
                    }
                ]
            }
            
            return ToolResult(ok=True, data=analytics)
            
        except MetaApiError as exc:
            logger.error("get_ar_performance_analytics_failed", **exc.to_dict())
            return ToolResult(ok=False, error=exc.to_dict())
        except Exception as exc:
            logger.error(f"get_ar_performance_analytics_error: {exc}")
            return ToolResult(ok=False, error={"message": str(exc)})


# Singleton pattern for engine access
_ar_vr_ads_engine: Optional[ARVRAdsEngine] = None


def get_ar_vr_ads_engine() -> ARVRAdsEngine:
    """Get the global ARVRAdsEngine instance"""
    global _ar_vr_ads_engine
    if _ar_vr_ads_engine is None:
        from .meta_client import get_client
        _ar_vr_ads_engine = ARVRAdsEngine(get_client())
    return _ar_vr_ads_engine

