"""
Strategic Recommendation Engine for Meta Ads MCP Server

This module provides high-level strategic recommendations that help LLMs
make sophisticated campaign management decisions based on comprehensive analysis.
"""

from typing import Dict, List, Any, Optional
from datetime import datetime
from dataclasses import dataclass
import statistics
from collections import defaultdict

from .meta_client import MetaClient
from .schemas import (
    PortfolioOptimizationRequest,
    ScalingRoadmapRequest,
    TestingStrategyRequest,
    AudienceStrategyRequest,
    CreativeStrategyRequest,
    BidStrategyMixRequest,
    PortfolioOptimizationResponse,
    ScalingRoadmapResponse,
    TestingStrategyResponse,
    AudienceStrategyResponse,
    CreativeStrategyResponse,
    BidStrategyMixResponse,
    PortfolioRecommendation,
    ScalingPhase,
    TestingPlan,
    AudienceRecommendation,
    CreativeRecommendation,
    BidStrategyRecommendation,
)
from .logging import get_logger

logger = get_logger(__name__)


@dataclass
class StrategicContext:
    """Context for strategic operations"""
    ad_account_id: str
    time_range: Dict[str, str]
    business_goals: List[str]
    constraints: Dict[str, Any]
    current_state: Dict[str, Any]


class StrategicRecommendationEngine:
    """Handles strategic recommendation operations for Meta Ads"""
    
    def __init__(self, client: MetaClient):
        self.client = client
    
    async def recommend_portfolio_optimization(
        self, 
        request: PortfolioOptimizationRequest
    ) -> PortfolioOptimizationResponse:
        """Provide holistic portfolio recommendations"""
        try:
            context = StrategicContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                business_goals=request.business_goals,
                constraints=request.constraints,
                current_state={}
            )
            
            # Analyze current portfolio state
            portfolio_analysis = await self._analyze_portfolio_state(context)
            
            # Generate optimization recommendations
            recommendations = await self._generate_portfolio_recommendations(
                portfolio_analysis, request.optimization_goals
            )
            
            # Calculate expected impact
            impact_analysis = await self._calculate_portfolio_impact(recommendations)
            
            # Generate implementation roadmap
            implementation_roadmap = await self._create_implementation_roadmap(
                recommendations, request.timeline_preferences
            )
            
            return PortfolioOptimizationResponse(
                recommendations=recommendations,
                impact_analysis=impact_analysis,
                implementation_roadmap=implementation_roadmap,
                portfolio_analysis=portfolio_analysis,
                business_goals=request.business_goals,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error generating portfolio optimization recommendations: {e}")
            raise
    
    async def recommend_scaling_roadmap(
        self, 
        request: ScalingRoadmapRequest
    ) -> ScalingRoadmapResponse:
        """Create step-by-step scaling plan with risk assessment"""
        try:
            context = StrategicContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                business_goals=request.business_goals,
                constraints=request.constraints,
                current_state={}
            )
            
            # Analyze current scaling potential
            scaling_analysis = await self._analyze_scaling_potential(context)
            
            # Create scaling phases
            scaling_phases = await self._create_scaling_phases(
                scaling_analysis, request.scaling_goals, request.risk_tolerance
            )
            
            # Calculate risk assessment
            risk_assessment = await self._assess_scaling_risks(scaling_phases)
            
            # Generate monitoring recommendations
            monitoring_plan = await self._create_monitoring_plan(scaling_phases)
            
            return ScalingRoadmapResponse(
                scaling_phases=scaling_phases,
                risk_assessment=risk_assessment,
                monitoring_plan=monitoring_plan,
                scaling_analysis=scaling_analysis,
                scaling_goals=request.scaling_goals,
                risk_tolerance=request.risk_tolerance,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error generating scaling roadmap: {e}")
            raise
    
    async def recommend_testing_strategy(
        self, 
        request: TestingStrategyRequest
    ) -> TestingStrategyResponse:
        """Create systematic testing plan"""
        try:
            context = StrategicContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                business_goals=request.business_goals,
                constraints=request.constraints,
                current_state={}
            )
            
            # Analyze current testing gaps
            testing_analysis = await self._analyze_testing_gaps(context)
            
            # Create testing plans
            testing_plans = await self._create_testing_plans(
                testing_analysis, request.testing_priorities, request.budget_allocation
            )
            
            # Calculate testing timeline
            testing_timeline = await self._create_testing_timeline(testing_plans)
            
            # Generate success metrics
            success_metrics = await self._define_testing_success_metrics(testing_plans)
            
            return TestingStrategyResponse(
                testing_plans=testing_plans,
                testing_timeline=testing_timeline,
                success_metrics=success_metrics,
                testing_analysis=testing_analysis,
                testing_priorities=request.testing_priorities,
                budget_allocation=request.budget_allocation,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error generating testing strategy: {e}")
            raise
    
    async def recommend_audience_strategy(
        self, 
        request: AudienceStrategyRequest
    ) -> AudienceStrategyResponse:
        """Create complete audience strategy"""
        try:
            context = StrategicContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                business_goals=request.business_goals,
                constraints=request.constraints,
                current_state={}
            )
            
            # Analyze current audience performance
            audience_analysis = await self._analyze_audience_performance(context)
            
            # Generate audience recommendations
            audience_recommendations = await self._generate_audience_recommendations(
                audience_analysis, request.audience_goals, request.expansion_strategy
            )
            
            # Create audience hierarchy
            audience_hierarchy = await self._create_audience_hierarchy(audience_recommendations)
            
            # Generate targeting recommendations
            targeting_recommendations = await self._generate_targeting_recommendations(
                audience_analysis, request.targeting_preferences
            )
            
            return AudienceStrategyResponse(
                audience_recommendations=audience_recommendations,
                audience_hierarchy=audience_hierarchy,
                targeting_recommendations=targeting_recommendations,
                audience_analysis=audience_analysis,
                audience_goals=request.audience_goals,
                expansion_strategy=request.expansion_strategy,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error generating audience strategy: {e}")
            raise
    
    async def recommend_creative_strategy(
        self, 
        request: CreativeStrategyRequest
    ) -> CreativeStrategyResponse:
        """Create creative direction based on what's working"""
        try:
            context = StrategicContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                business_goals=request.business_goals,
                constraints=request.constraints,
                current_state={}
            )
            
            # Analyze current creative performance
            creative_analysis = await self._analyze_creative_performance(context)
            
            # Generate creative recommendations
            creative_recommendations = await self._generate_creative_recommendations(
                creative_analysis, request.creative_goals, request.creative_preferences
            )
            
            # Create creative testing plan
            creative_testing_plan = await self._create_creative_testing_plan(
                creative_analysis, request.testing_budget
            )
            
            # Generate production recommendations
            production_recommendations = await self._generate_production_recommendations(
                creative_analysis, request.production_constraints
            )
            
            return CreativeStrategyResponse(
                creative_recommendations=creative_recommendations,
                creative_testing_plan=creative_testing_plan,
                production_recommendations=production_recommendations,
                creative_analysis=creative_analysis,
                creative_goals=request.creative_goals,
                creative_preferences=request.creative_preferences,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error generating creative strategy: {e}")
            raise
    
    async def recommend_bid_strategy_mix(
        self, 
        request: BidStrategyMixRequest
    ) -> BidStrategyMixResponse:
        """Create optimal bid strategy distribution"""
        try:
            context = StrategicContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                business_goals=request.business_goals,
                constraints=request.constraints,
                current_state={}
            )
            
            # Analyze current bid strategy performance
            bid_analysis = await self._analyze_bid_strategy_performance(context)
            
            # Generate bid strategy recommendations
            bid_recommendations = await self._generate_bid_recommendations(
                bid_analysis, request.bid_goals, request.optimization_preferences
            )
            
            # Create bid strategy allocation
            strategy_allocation = await self._create_strategy_allocation(
                bid_recommendations, request.budget_distribution
            )
            
            # Generate bid optimization plan
            optimization_plan = await self._create_bid_optimization_plan(
                bid_analysis, request.optimization_timeline
            )
            
            return BidStrategyMixResponse(
                bid_recommendations=bid_recommendations,
                strategy_allocation=strategy_allocation,
                optimization_plan=optimization_plan,
                bid_analysis=bid_analysis,
                bid_goals=request.bid_goals,
                optimization_preferences=request.optimization_preferences,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error generating bid strategy mix: {e}")
            raise
    
    async def _analyze_portfolio_state(self, context: StrategicContext) -> Dict[str, Any]:
        """Analyze current portfolio state"""
        try:
            # Get all campaigns
            campaigns_response = await self.client.graph_request(
                method="GET",
                path=f"{context.ad_account_id}/campaigns",
                params={
                    "fields": "id,name,objective,status,daily_budget,lifetime_budget,created_time",
                    "limit": 1000
                }
            )
            
            campaigns = campaigns_response.get("data", [])
            
            # Get campaign insights
            insights_response = await self.client.graph_request(
                method="GET",
                path=f"{context.ad_account_id}/insights",
                params={
                    "level": "campaign",
                    "fields": "spend,conversions,impressions,clicks,ctr,cpc,roas",
                    "time_range": context.time_range,
                    "limit": 1000
                }
            )
            
            insights = insights_response.get("data", [])
            
            # Analyze portfolio metrics
            total_spend = sum(float(insight.get("spend", 0)) for insight in insights)
            total_conversions = sum(float(insight.get("conversions", 0)) for insight in insights)
            total_impressions = sum(int(insight.get("impressions", 0)) for insight in insights)
            total_clicks = sum(int(insight.get("clicks", 0)) for insight in insights)
            
            # Calculate portfolio efficiency
            portfolio_roas = (total_conversions / total_spend) if total_spend > 0 else 0
            portfolio_ctr = (total_clicks / total_impressions * 100) if total_impressions > 0 else 0
            portfolio_cpc = (total_spend / total_clicks) if total_clicks > 0 else 0
            
            # Analyze objective distribution
            objective_distribution = defaultdict(int)
            for campaign in campaigns:
                objective = campaign.get("objective", "unknown")
                objective_distribution[objective] += 1
            
            # Analyze status distribution
            status_distribution = defaultdict(int)
            for campaign in campaigns:
                status = campaign.get("status", "unknown")
                status_distribution[status] += 1
            
            return {
                "total_campaigns": len(campaigns),
                "total_spend": total_spend,
                "total_conversions": total_conversions,
                "total_impressions": total_impressions,
                "total_clicks": total_clicks,
                "portfolio_roas": portfolio_roas,
                "portfolio_ctr": portfolio_ctr,
                "portfolio_cpc": portfolio_cpc,
                "objective_distribution": dict(objective_distribution),
                "status_distribution": dict(status_distribution),
                "active_campaigns": status_distribution.get("ACTIVE", 0),
                "paused_campaigns": status_distribution.get("PAUSED", 0)
            }
            
        except Exception as e:
            logger.error(f"Error analyzing portfolio state: {e}")
            return {}
    
    async def _generate_portfolio_recommendations(
        self, 
        portfolio_analysis: Dict[str, Any], 
        optimization_goals: List[str]
    ) -> List[PortfolioRecommendation]:
        """Generate portfolio optimization recommendations"""
        try:
            recommendations = []
            
            # Budget allocation recommendations
            if "optimize_budget_allocation" in optimization_goals:
                recommendations.append(PortfolioRecommendation(
                    category="budget_allocation",
                    priority="high",
                    title="Optimize Budget Allocation",
                    description="Redistribute budgets based on performance to maximize ROI",
                    expected_impact="15-25% ROAS improvement",
                    implementation_effort="medium",
                    risk_level="low",
                    timeline="1-2 weeks",
                    specific_actions=[
                        "Identify top-performing campaigns",
                        "Increase budgets for high-ROAS campaigns",
                        "Reduce budgets for underperforming campaigns",
                        "Implement budget caps for risk management"
                    ]
                ))
            
            # Objective diversification
            if "diversify_objectives" in optimization_goals:
                recommendations.append(PortfolioRecommendation(
                    category="objective_diversification",
                    priority="medium",
                    title="Diversify Campaign Objectives",
                    description="Add new campaign objectives to capture different conversion paths",
                    expected_impact="10-20% reach increase",
                    implementation_effort="high",
                    risk_level="medium",
                    timeline="2-4 weeks",
                    specific_actions=[
                        "Analyze current objective performance",
                        "Identify gaps in conversion funnel",
                        "Create new campaigns with different objectives",
                        "Test and optimize new objectives"
                    ]
                ))
            
            # Performance optimization
            if "improve_performance" in optimization_goals:
                recommendations.append(PortfolioRecommendation(
                    category="performance_optimization",
                    priority="high",
                    title="Improve Overall Performance",
                    description="Optimize underperforming campaigns and scale winners",
                    expected_impact="20-30% performance improvement",
                    implementation_effort="medium",
                    risk_level="low",
                    timeline="1-3 weeks",
                    specific_actions=[
                        "Pause underperforming campaigns",
                        "Scale high-performing campaigns",
                        "Optimize targeting and creatives",
                        "Implement automated rules"
                    ]
                ))
            
            return recommendations
            
        except Exception as e:
            logger.error(f"Error generating portfolio recommendations: {e}")
            return []
    
    async def _analyze_scaling_potential(self, context: StrategicContext) -> Dict[str, Any]:
        """Analyze current scaling potential"""
        try:
            # Get campaign performance data
            insights_response = await self.client.graph_request(
                method="GET",
                path=f"{context.ad_account_id}/insights",
                params={
                    "level": "campaign",
                    "fields": "spend,conversions,impressions,clicks,ctr,cpc,roas",
                    "time_range": context.time_range,
                    "limit": 1000
                }
            )
            
            insights = insights_response.get("data", [])
            
            # Analyze scaling metrics
            total_spend = sum(float(insight.get("spend", 0)) for insight in insights)
            total_conversions = sum(float(insight.get("conversions", 0)) for insight in insights)
            avg_roas = statistics.mean([float(insight.get("roas", 0)) for insight in insights if insight.get("roas", 0) > 0]) if insights else 0
            
            # Identify scaling opportunities
            high_performing_campaigns = [insight for insight in insights if float(insight.get("roas", 0)) > 3.0]
            scaling_potential = len(high_performing_campaigns) / len(insights) if insights else 0
            
            return {
                "total_spend": total_spend,
                "total_conversions": total_conversions,
                "average_roas": avg_roas,
                "scaling_potential": scaling_potential,
                "high_performing_campaigns": len(high_performing_campaigns),
                "total_campaigns": len(insights),
                "scaling_readiness": "high" if scaling_potential > 0.3 else "medium" if scaling_potential > 0.1 else "low"
            }
            
        except Exception as e:
            logger.error(f"Error analyzing scaling potential: {e}")
            return {}
    
    async def _create_scaling_phases(
        self, 
        scaling_analysis: Dict[str, Any], 
        scaling_goals: List[str], 
        risk_tolerance: str
    ) -> List[ScalingPhase]:
        """Create scaling phases"""
        try:
            phases = []
            
            # Phase 1: Foundation
            phases.append(ScalingPhase(
                phase_name="Foundation",
                phase_order=1,
                duration_weeks=2,
                budget_increase_percentage=20,
                risk_level="low",
                objectives=[
                    "Optimize current high-performing campaigns",
                    "Pause underperforming campaigns",
                    "Implement basic automation rules"
                ],
                success_metrics={
                    "roas_improvement": "10-15%",
                    "spend_efficiency": "5-10%",
                    "campaign_stability": "95%+"
                },
                prerequisites=[],
                deliverables=[
                    "Optimized campaign structure",
                    "Automated rules implemented",
                    "Performance baseline established"
                ]
            ))
            
            # Phase 2: Controlled Growth
            phases.append(ScalingPhase(
                phase_name="Controlled Growth",
                phase_order=2,
                duration_weeks=4,
                budget_increase_percentage=50,
                risk_level="medium",
                objectives=[
                    "Scale winning campaigns",
                    "Test new audiences",
                    "Expand creative testing"
                ],
                success_metrics={
                    "roas_improvement": "20-30%",
                    "spend_increase": "40-60%",
                    "conversion_volume": "50-80%"
                },
                prerequisites=["Foundation phase completed"],
                deliverables=[
                    "Scaled campaign budgets",
                    "New audience tests launched",
                    "Creative testing framework"
                ]
            ))
            
            # Phase 3: Aggressive Scaling
            if risk_tolerance in ["high", "medium"]:
                phases.append(ScalingPhase(
                    phase_name="Aggressive Scaling",
                    phase_order=3,
                    duration_weeks=6,
                    budget_increase_percentage=100,
                    risk_level="high",
                    objectives=[
                        "Maximum budget allocation",
                        "Advanced audience expansion",
                        "Creative optimization at scale"
                    ],
                    success_metrics={
                        "roas_improvement": "30-50%",
                        "spend_increase": "80-120%",
                        "market_penetration": "Significant"
                    },
                    prerequisites=["Controlled Growth phase completed"],
                    deliverables=[
                        "Maximum budget utilization",
                        "Advanced targeting strategies",
                        "Scaled creative operations"
                    ]
                ))
            
            return phases
            
        except Exception as e:
            logger.error(f"Error creating scaling phases: {e}")
            return []
    
    async def _analyze_testing_gaps(self, context: StrategicContext) -> Dict[str, Any]:
        """Analyze current testing gaps"""
        try:
            # Get campaign data
            campaigns_response = await self.client.graph_request(
                method="GET",
                path=f"{context.ad_account_id}/campaigns",
                params={
                    "fields": "id,name,objective,status",
                    "limit": 1000
                }
            )
            
            campaigns = campaigns_response.get("data", [])
            
            # Analyze testing coverage
            objectives_tested = set(campaign.get("objective") for campaign in campaigns)
            len(objectives_tested)
            
            # Identify testing gaps
            common_objectives = ["LINK_CLICKS", "CONVERSIONS", "LEAD_GENERATION", "BRAND_AWARENESS", "REACH"]
            missing_objectives = [obj for obj in common_objectives if obj not in objectives_tested]
            
            return {
                "total_campaigns": len(campaigns),
                "objectives_tested": list(objectives_tested),
                "missing_objectives": missing_objectives,
                "testing_coverage": len(objectives_tested) / len(common_objectives) * 100,
                "testing_gaps": {
                    "objectives": len(missing_objectives),
                    "audiences": "medium",  # Would analyze actual audience diversity
                    "creatives": "high",    # Would analyze creative diversity
                    "bidding": "low"        # Would analyze bid strategy diversity
                }
            }
            
        except Exception as e:
            logger.error(f"Error analyzing testing gaps: {e}")
            return {}
    
    async def _create_testing_plans(
        self, 
        testing_analysis: Dict[str, Any], 
        testing_priorities: List[str], 
        budget_allocation: Dict[str, float]
    ) -> List[TestingPlan]:
        """Create testing plans"""
        try:
            plans = []
            
            # Creative Testing Plan
            if "creative_testing" in testing_priorities:
                plans.append(TestingPlan(
                    test_type="creative_testing",
                    priority="high",
                    budget_percentage=budget_allocation.get("creative_testing", 30),
                    duration_weeks=4,
                    test_description="Test different creative formats, messaging, and visuals",
                    success_metrics=["ctr", "conversion_rate", "roas"],
                    test_variants=[
                        "Image vs Video",
                        "Different messaging angles",
                        "Various call-to-action buttons",
                        "Different creative formats"
                    ],
                    expected_outcomes={
                        "ctr_improvement": "15-25%",
                        "conversion_rate_improvement": "10-20%",
                        "creative_fatigue_reduction": "30-50%"
                    },
                    implementation_steps=[
                        "Create creative variations",
                        "Set up A/B test campaigns",
                        "Monitor performance daily",
                        "Scale winning creatives"
                    ]
                ))
            
            # Audience Testing Plan
            if "audience_testing" in testing_priorities:
                plans.append(TestingPlan(
                    test_type="audience_testing",
                    priority="high",
                    budget_percentage=budget_allocation.get("audience_testing", 25),
                    duration_weeks=6,
                    test_description="Test new audience segments and targeting strategies",
                    success_metrics=["cpc", "conversion_rate", "roas"],
                    test_variants=[
                        "Lookalike audiences",
                        "Interest-based targeting",
                        "Behavioral targeting",
                        "Custom audiences"
                    ],
                    expected_outcomes={
                        "cpc_reduction": "10-20%",
                        "audience_expansion": "50-100%",
                        "conversion_quality_improvement": "15-25%"
                    },
                    implementation_steps=[
                        "Create audience segments",
                        "Set up audience test campaigns",
                        "Monitor audience performance",
                        "Optimize targeting parameters"
                    ]
                ))
            
            # Bid Strategy Testing Plan
            if "bid_strategy_testing" in testing_priorities:
                plans.append(TestingPlan(
                    test_type="bid_strategy_testing",
                    priority="medium",
                    budget_percentage=budget_allocation.get("bid_strategy_testing", 20),
                    duration_weeks=3,
                    test_description="Test different bidding strategies and bid amounts",
                    success_metrics=["cpc", "conversion_volume", "roas"],
                    test_variants=[
                        "Cost per click vs Cost per conversion",
                        "Bid cap vs Target cost",
                        "Automatic vs Manual bidding",
                        "Different bid amounts"
                    ],
                    expected_outcomes={
                        "bid_efficiency_improvement": "20-30%",
                        "conversion_volume_increase": "25-40%",
                        "cost_optimization": "15-25%"
                    },
                    implementation_steps=[
                        "Set up bid strategy tests",
                        "Monitor bid performance",
                        "Adjust bid parameters",
                        "Scale winning strategies"
                    ]
                ))
            
            return plans
            
        except Exception as e:
            logger.error(f"Error creating testing plans: {e}")
            return []
    
    async def _analyze_audience_performance(self, context: StrategicContext) -> Dict[str, Any]:
        """Analyze current audience performance"""
        try:
            # Get insights with audience breakdown
            insights_response = await self.client.graph_request(
                method="GET",
                path=f"{context.ad_account_id}/insights",
                params={
                    "level": "adset",
                    "fields": "spend,conversions,impressions,clicks,ctr,cpc,roas,reach,frequency",
                    "time_range": context.time_range,
                    "limit": 1000
                }
            )
            
            insights = insights_response.get("data", [])
            
            # Analyze audience metrics
            total_reach = sum(int(insight.get("reach", 0)) for insight in insights)
            avg_frequency = statistics.mean([float(insight.get("frequency", 0)) for insight in insights if insight.get("frequency", 0) > 0]) if insights else 0
            avg_cpc = statistics.mean([float(insight.get("cpc", 0)) for insight in insights if insight.get("cpc", 0) > 0]) if insights else 0
            
            return {
                "total_reach": total_reach,
                "average_frequency": avg_frequency,
                "average_cpc": avg_cpc,
                "total_adsets": len(insights),
                "audience_diversity": "medium",  # Would analyze actual audience diversity
                "targeting_efficiency": "high" if avg_cpc < 2.0 else "medium" if avg_cpc < 5.0 else "low"
            }
            
        except Exception as e:
            logger.error(f"Error analyzing audience performance: {e}")
            return {}
    
    async def _generate_audience_recommendations(
        self, 
        audience_analysis: Dict[str, Any], 
        audience_goals: List[str], 
        expansion_strategy: str
    ) -> List[AudienceRecommendation]:
        """Generate audience recommendations"""
        try:
            recommendations = []
            
            # Lookalike Audience Recommendation
            if "expand_reach" in audience_goals:
                recommendations.append(AudienceRecommendation(
                    audience_type="lookalike",
                    priority="high",
                    title="Create Lookalike Audiences",
                    description="Create lookalike audiences based on your best customers",
                    expected_impact="50-100% reach increase",
                    implementation_effort="low",
                    risk_level="low",
                    targeting_parameters={
                        "source_audience": "customers",
                        "lookalike_percentage": "1-3%",
                        "countries": ["US", "CA", "GB"],
                        "age_range": "25-65"
                    },
                    budget_recommendation="20-30% of total budget",
                    success_metrics=["reach", "cpc", "conversion_rate"],
                    implementation_steps=[
                        "Create customer custom audience",
                        "Generate 1% lookalike audience",
                        "Test with small budget",
                        "Scale based on performance"
                    ]
                ))
            
            # Interest-Based Targeting Recommendation
            if "improve_targeting" in audience_goals:
                recommendations.append(AudienceRecommendation(
                    audience_type="interest_based",
                    priority="medium",
                    title="Expand Interest-Based Targeting",
                    description="Test new interest categories to find untapped audiences",
                    expected_impact="30-50% audience expansion",
                    implementation_effort="medium",
                    risk_level="medium",
                    targeting_parameters={
                        "interests": ["technology", "business", "finance"],
                        "behaviors": ["frequent_travelers", "online_shoppers"],
                        "demographics": {"age_min": 25, "age_max": 55}
                    },
                    budget_recommendation="15-25% of total budget",
                    success_metrics=["cpc", "conversion_rate", "audience_quality"],
                    implementation_steps=[
                        "Research relevant interests",
                        "Create interest-based audiences",
                        "Test with small budgets",
                        "Optimize based on performance"
                    ]
                ))
            
            return recommendations
            
        except Exception as e:
            logger.error(f"Error generating audience recommendations: {e}")
            return []
    
    async def _analyze_creative_performance(self, context: StrategicContext) -> Dict[str, Any]:
        """Analyze current creative performance"""
        try:
            # Get ad insights
            insights_response = await self.client.graph_request(
                method="GET",
                path=f"{context.ad_account_id}/insights",
                params={
                    "level": "ad",
                    "fields": "spend,conversions,impressions,clicks,ctr,cpc,roas,frequency",
                    "time_range": context.time_range,
                    "limit": 1000
                }
            )
            
            insights = insights_response.get("data", [])
            
            # Analyze creative metrics
            avg_ctr = statistics.mean([float(insight.get("ctr", 0)) for insight in insights if insight.get("ctr", 0) > 0]) if insights else 0
            avg_frequency = statistics.mean([float(insight.get("frequency", 0)) for insight in insights if insight.get("frequency", 0) > 0]) if insights else 0
            
            # Identify creative fatigue
            fatigued_creatives = [insight for insight in insights if float(insight.get("frequency", 0)) > 3.0 and float(insight.get("ctr", 0)) < 1.0]
            
            return {
                "total_ads": len(insights),
                "average_ctr": avg_ctr,
                "average_frequency": avg_frequency,
                "fatigued_creatives": len(fatigued_creatives),
                "creative_diversity": "low",  # Would analyze actual creative diversity
                "performance_variance": "high" if len(fatigued_creatives) > len(insights) * 0.3 else "medium"
            }
            
        except Exception as e:
            logger.error(f"Error analyzing creative performance: {e}")
            return {}
    
    async def _generate_creative_recommendations(
        self, 
        creative_analysis: Dict[str, Any], 
        creative_goals: List[str], 
        creative_preferences: Dict[str, Any]
    ) -> List[CreativeRecommendation]:
        """Generate creative recommendations"""
        try:
            recommendations = []
            
            # Creative Refresh Recommendation
            if "reduce_fatigue" in creative_goals:
                recommendations.append(CreativeRecommendation(
                    creative_type="refresh",
                    priority="high",
                    title="Refresh Fatigued Creatives",
                    description="Replace underperforming creatives with fresh content",
                    expected_impact="20-30% CTR improvement",
                    implementation_effort="medium",
                    risk_level="low",
                    creative_specifications={
                        "format": "image_and_video",
                        "aspect_ratio": "1:1, 16:9, 9:16",
                        "text_length": "short_to_medium",
                        "call_to_action": "varied"
                    },
                    budget_recommendation="25-35% of total budget",
                    success_metrics=["ctr", "frequency", "conversion_rate"],
                    implementation_steps=[
                        "Identify fatigued creatives",
                        "Create new creative variations",
                        "Test new creatives",
                        "Replace underperforming ones"
                    ]
                ))
            
            # Video Creative Recommendation
            if "expand_formats" in creative_goals:
                recommendations.append(CreativeRecommendation(
                    creative_type="video",
                    priority="medium",
                    title="Expand Video Creative Testing",
                    description="Test video formats to improve engagement and performance",
                    expected_impact="15-25% engagement increase",
                    implementation_effort="high",
                    risk_level="medium",
                    creative_specifications={
                        "format": "video",
                        "duration": "15-30_seconds",
                        "aspect_ratio": "16:9, 9:16, 1:1",
                        "content_type": "product_demo, testimonial, lifestyle"
                    },
                    budget_recommendation="20-30% of total budget",
                    success_metrics=["engagement_rate", "video_views", "conversion_rate"],
                    implementation_steps=[
                        "Create video creative concepts",
                        "Produce video content",
                        "Test video vs image performance",
                        "Scale winning video formats"
                    ]
                ))
            
            return recommendations
            
        except Exception as e:
            logger.error(f"Error generating creative recommendations: {e}")
            return []
    
    async def _analyze_bid_strategy_performance(self, context: StrategicContext) -> Dict[str, Any]:
        """Analyze current bid strategy performance"""
        try:
            # Get campaign insights
            insights_response = await self.client.graph_request(
                method="GET",
                path=f"{context.ad_account_id}/insights",
                params={
                    "level": "campaign",
                    "fields": "spend,conversions,impressions,clicks,ctr,cpc,roas",
                    "time_range": context.time_range,
                    "limit": 1000
                }
            )
            
            insights = insights_response.get("data", [])
            
            # Analyze bid performance
            avg_cpc = statistics.mean([float(insight.get("cpc", 0)) for insight in insights if insight.get("cpc", 0) > 0]) if insights else 0
            avg_roas = statistics.mean([float(insight.get("roas", 0)) for insight in insights if insight.get("roas", 0) > 0]) if insights else 0
            
            return {
                "total_campaigns": len(insights),
                "average_cpc": avg_cpc,
                "average_roas": avg_roas,
                "bid_efficiency": "high" if avg_cpc < 2.0 and avg_roas > 3.0 else "medium" if avg_cpc < 5.0 and avg_roas > 2.0 else "low",
                "strategy_diversity": "low"  # Would analyze actual bid strategy diversity
            }
            
        except Exception as e:
            logger.error(f"Error analyzing bid strategy performance: {e}")
            return {}
    
    async def _generate_bid_recommendations(
        self, 
        bid_analysis: Dict[str, Any], 
        bid_goals: List[str], 
        optimization_preferences: Dict[str, Any]
    ) -> List[BidStrategyRecommendation]:
        """Generate bid strategy recommendations"""
        try:
            recommendations = []
            
            # Cost Per Conversion Strategy
            if "optimize_conversions" in bid_goals:
                recommendations.append(BidStrategyRecommendation(
                    bid_strategy="cost_per_conversion",
                    priority="high",
                    title="Implement Cost Per Conversion Bidding",
                    description="Use cost per conversion bidding to optimize for conversions",
                    expected_impact="20-30% conversion volume increase",
                    implementation_effort="low",
                    risk_level="low",
                    bid_parameters={
                        "bid_strategy": "COST_PER_CONVERSION",
                        "target_cost": "optimize_based_on_historical_data",
                        "optimization_goal": "conversions"
                    },
                    budget_recommendation="40-50% of total budget",
                    success_metrics=["conversion_volume", "cost_per_conversion", "roas"],
                    implementation_steps=[
                        "Analyze historical conversion costs",
                        "Set target cost per conversion",
                        "Implement cost per conversion bidding",
                        "Monitor and adjust target costs"
                    ]
                ))
            
            # Bid Cap Strategy
            if "control_costs" in bid_goals:
                recommendations.append(BidStrategyRecommendation(
                    bid_strategy="bid_cap",
                    priority="medium",
                    title="Implement Bid Cap Strategy",
                    description="Use bid caps to control maximum bid amounts",
                    expected_impact="15-25% cost control improvement",
                    implementation_effort="medium",
                    risk_level="medium",
                    bid_parameters={
                        "bid_strategy": "BID_CAP",
                        "bid_cap": "based_on_historical_cpc",
                        "optimization_goal": "link_clicks"
                    },
                    budget_recommendation="30-40% of total budget",
                    success_metrics=["cpc", "spend_control", "impression_volume"],
                    implementation_steps=[
                        "Calculate optimal bid caps",
                        "Set bid cap limits",
                        "Monitor bid cap performance",
                        "Adjust caps based on results"
                    ]
                ))
            
            return recommendations
            
        except Exception as e:
            logger.error(f"Error generating bid recommendations: {e}")
            return []
    
    async def _calculate_portfolio_impact(self, recommendations: List[PortfolioRecommendation]) -> Dict[str, Any]:
        """Calculate expected portfolio impact"""
        try:
            total_expected_impact = 0
            high_impact_recommendations = 0
            
            for rec in recommendations:
                if rec.priority == "high":
                    high_impact_recommendations += 1
                    # Extract impact percentage from expected_impact string
                    impact_str = rec.expected_impact
                    if "%" in impact_str:
                        try:
                            impact_value = float(impact_str.split("%")[0].split("-")[-1])
                            total_expected_impact += impact_value
                        except (ValueError, IndexError):
                            pass
            
            return {
                "total_recommendations": len(recommendations),
                "high_priority_recommendations": high_impact_recommendations,
                "expected_roas_improvement": f"{total_expected_impact:.1f}%",
                "implementation_timeline": "4-8 weeks",
                "risk_level": "low" if high_impact_recommendations <= 2 else "medium"
            }
            
        except Exception as e:
            logger.error(f"Error calculating portfolio impact: {e}")
            return {}
    
    async def _create_implementation_roadmap(
        self, 
        recommendations: List[PortfolioRecommendation], 
        timeline_preferences: Dict[str, Any]
    ) -> List[Dict[str, Any]]:
        """Create implementation roadmap"""
        try:
            roadmap = []
            
            # Sort recommendations by priority
            sorted_recommendations = sorted(recommendations, key=lambda x: {"high": 1, "medium": 2, "low": 3}[x.priority])
            
            current_week = 1
            for rec in sorted_recommendations:
                roadmap.append({
                    "week": current_week,
                    "recommendation": rec.title,
                    "category": rec.category,
                    "priority": rec.priority,
                    "duration": rec.timeline,
                    "actions": rec.specific_actions[:3],  # First 3 actions
                    "success_metrics": rec.expected_impact
                })
                current_week += 2  # Assume 2 weeks per recommendation
            
            return roadmap
            
        except Exception as e:
            logger.error(f"Error creating implementation roadmap: {e}")
            return []
    
    async def _assess_scaling_risks(self, scaling_phases: List[ScalingPhase]) -> Dict[str, Any]:
        """Assess scaling risks"""
        try:
            total_risk_score = 0
            high_risk_phases = 0
            
            for phase in scaling_phases:
                if phase.risk_level == "high":
                    high_risk_phases += 1
                    total_risk_score += 3
                elif phase.risk_level == "medium":
                    total_risk_score += 2
                else:
                    total_risk_score += 1
            
            avg_risk_score = total_risk_score / len(scaling_phases) if scaling_phases else 0
            
            return {
                "overall_risk_level": "high" if avg_risk_score > 2.5 else "medium" if avg_risk_score > 1.5 else "low",
                "high_risk_phases": high_risk_phases,
                "total_phases": len(scaling_phases),
                "risk_mitigation_strategies": [
                    "Implement budget caps",
                    "Monitor performance daily",
                    "Have rollback plans ready",
                    "Test with small budgets first"
                ]
            }
            
        except Exception as e:
            logger.error(f"Error assessing scaling risks: {e}")
            return {}
    
    async def _create_monitoring_plan(self, scaling_phases: List[ScalingPhase]) -> Dict[str, Any]:
        """Create monitoring plan"""
        try:
            return {
                "monitoring_frequency": "daily",
                "key_metrics": ["roas", "cpc", "conversion_rate", "spend_pacing"],
                "alert_thresholds": {
                    "roas_drop": "20%",
                    "cpc_increase": "30%",
                    "spend_pacing": "10% ahead or behind"
                },
                "reporting_schedule": "weekly",
                "escalation_procedures": [
                    "Daily monitoring for first 2 weeks",
                    "Weekly reports to stakeholders",
                    "Immediate alerts for significant changes"
                ]
            }
            
        except Exception as e:
            logger.error(f"Error creating monitoring plan: {e}")
            return {}
    
    async def _create_testing_timeline(self, testing_plans: List[TestingPlan]) -> List[Dict[str, Any]]:
        """Create testing timeline"""
        try:
            timeline = []
            current_week = 1
            
            for plan in testing_plans:
                timeline.append({
                    "week": current_week,
                    "test_type": plan.test_type,
                    "duration": plan.duration_weeks,
                    "budget_percentage": plan.budget_percentage,
                    "description": plan.test_description,
                    "expected_outcomes": plan.expected_outcomes
                })
                current_week += plan.duration_weeks
            
            return timeline
            
        except Exception as e:
            logger.error(f"Error creating testing timeline: {e}")
            return []
    
    async def _define_testing_success_metrics(self, testing_plans: List[TestingPlan]) -> Dict[str, Any]:
        """Define testing success metrics"""
        try:
            return {
                "primary_metrics": ["roas", "cpc", "conversion_rate"],
                "secondary_metrics": ["ctr", "frequency", "reach"],
                "success_thresholds": {
                    "roas_improvement": "15%",
                    "cpc_reduction": "10%",
                    "conversion_rate_improvement": "20%"
                },
                "measurement_period": "2-4 weeks",
                "statistical_significance": "95% confidence level"
            }
            
        except Exception as e:
            logger.error(f"Error defining testing success metrics: {e}")
            return {}
    
    async def _create_audience_hierarchy(self, audience_recommendations: List[AudienceRecommendation]) -> Dict[str, Any]:
        """Create audience hierarchy"""
        try:
            return {
                "tier_1": "Core audiences (high-value customers)",
                "tier_2": "Lookalike audiences (1-3%)",
                "tier_3": "Interest-based audiences",
                "tier_4": "Behavioral audiences",
                "budget_allocation": {
                    "tier_1": "40%",
                    "tier_2": "30%",
                    "tier_3": "20%",
                    "tier_4": "10%"
                }
            }
            
        except Exception as e:
            logger.error(f"Error creating audience hierarchy: {e}")
            return {}
    
    async def _generate_targeting_recommendations(
        self, 
        audience_analysis: Dict[str, Any], 
        targeting_preferences: Dict[str, Any]
    ) -> List[Dict[str, Any]]:
        """Generate targeting recommendations"""
        try:
            return [
                {
                    "recommendation": "Expand age ranges",
                    "current_range": "25-45",
                    "recommended_range": "22-55",
                    "expected_impact": "20-30% reach increase"
                },
                {
                    "recommendation": "Add mobile-specific targeting",
                    "current_setting": "all_devices",
                    "recommended_setting": "mobile_optimized",
                    "expected_impact": "15-25% mobile performance improvement"
                }
            ]
            
        except Exception as e:
            logger.error(f"Error generating targeting recommendations: {e}")
            return []
    
    async def _create_creative_testing_plan(
        self, 
        creative_analysis: Dict[str, Any], 
        testing_budget: float
    ) -> Dict[str, Any]:
        """Create creative testing plan"""
        try:
            return {
                "testing_budget": testing_budget,
                "test_variants": [
                    "Image vs Video",
                    "Different messaging angles",
                    "Various call-to-action buttons"
                ],
                "testing_duration": "4 weeks",
                "success_metrics": ["ctr", "conversion_rate", "engagement_rate"],
                "scaling_criteria": "20% improvement in primary metrics"
            }
            
        except Exception as e:
            logger.error(f"Error creating creative testing plan: {e}")
            return {}
    
    async def _generate_production_recommendations(
        self, 
        creative_analysis: Dict[str, Any], 
        production_constraints: Dict[str, Any]
    ) -> List[Dict[str, Any]]:
        """Generate production recommendations"""
        try:
            return [
                {
                    "recommendation": "Increase video production",
                    "current_ratio": "20% video, 80% image",
                    "recommended_ratio": "40% video, 60% image",
                    "expected_impact": "25-35% engagement improvement"
                },
                {
                    "recommendation": "Create mobile-optimized formats",
                    "current_formats": "square_images",
                    "recommended_formats": "vertical_videos, story_formats",
                    "expected_impact": "30-40% mobile performance improvement"
                }
            ]
            
        except Exception as e:
            logger.error(f"Error generating production recommendations: {e}")
            return []
    
    async def _create_strategy_allocation(
        self, 
        bid_recommendations: List[BidStrategyRecommendation], 
        budget_distribution: Dict[str, float]
    ) -> Dict[str, Any]:
        """Create bid strategy allocation"""
        try:
            allocation = {}
            sum(budget_distribution.values()) if budget_distribution else 100
            
            for rec in bid_recommendations:
                strategy_name = rec.bid_strategy.replace("_", " ").title()
                allocation[strategy_name] = {
                    "budget_percentage": rec.budget_recommendation,
                    "priority": rec.priority,
                    "expected_impact": rec.expected_impact
                }
            
            return allocation
            
        except Exception as e:
            logger.error(f"Error creating strategy allocation: {e}")
            return {}
    
    async def _create_bid_optimization_plan(
        self, 
        bid_analysis: Dict[str, Any], 
        optimization_timeline: str
    ) -> Dict[str, Any]:
        """Create bid optimization plan"""
        try:
            return {
                "optimization_timeline": optimization_timeline,
                "optimization_phases": [
                    "Phase 1: Analyze current performance (Week 1)",
                    "Phase 2: Implement new bid strategies (Week 2-3)",
                    "Phase 3: Monitor and adjust (Week 4-6)",
                    "Phase 4: Scale winning strategies (Week 7+)"
                ],
                "success_metrics": ["roas", "cpc", "conversion_volume"],
                "optimization_frequency": "weekly",
                "adjustment_threshold": "10% performance change"
            }
            
        except Exception as e:
            logger.error(f"Error creating bid optimization plan: {e}")
            return {}


# Global strategic engine instance
_strategic_engine: Optional[StrategicRecommendationEngine] = None


def get_strategic_engine() -> StrategicRecommendationEngine:
    """Get the global StrategicRecommendationEngine instance"""
    global _strategic_engine
    if _strategic_engine is None:
        from .meta_client import get_client
        _strategic_engine = StrategicRecommendationEngine(get_client())
    return _strategic_engine

