"""
Expert Workflow Automation for Meta Ads MCP Server

This module provides workflows that embody advertising best practices,
enabling LLMs to execute complex multi-step processes with a single call.
"""

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

from .meta_client import MetaClient
from .schemas import (
    NewAccountSetupRequest,
    ScaleProfitablyRequest,
    CreativeTestingFrameworkRequest,
    AudienceExpansionLadderRequest,
    TroubleshootPerformanceRequest,
    SeasonalPreparationRequest,
    CostReductionAuditRequest,
    NewAccountSetupResponse,
    ScaleProfitablyResponse,
    CreativeTestingFrameworkResponse,
    AudienceExpansionLadderResponse,
    TroubleshootPerformanceResponse,
    SeasonalPreparationResponse,
    CostReductionAuditResponse,
    WorkflowStep,
    DiagnosticResult,
    OptimizationAction,
)
from .logging import get_logger

logger = get_logger(__name__)


@dataclass
class WorkflowContext:
    """Context for workflow operations"""
    ad_account_id: str
    workflow_type: str
    parameters: Dict[str, Any]
    steps_completed: List[str]
    current_state: Dict[str, Any]


class ExpertWorkflowEngine:
    """Handles expert workflow automation for Meta Ads"""
    
    def __init__(self, client: MetaClient):
        self.client = client
    
    async def execute_new_account_setup(
        self, 
        request: NewAccountSetupRequest
    ) -> NewAccountSetupResponse:
        """Full account setup done right from start"""
        try:
            context = WorkflowContext(
                ad_account_id=request.ad_account_id,
                workflow_type="new_account_setup",
                parameters=request.setup_parameters,
                steps_completed=[],
                current_state={}
            )
            
            workflow_steps = []
            
            # Step 1: Account Configuration
            step1 = await self._setup_account_configuration(context, request.business_info)
            workflow_steps.append(step1)
            context.steps_completed.append("account_configuration")
            
            # Step 2: Pixel Setup
            step2 = await self._setup_conversion_tracking(context, request.tracking_requirements)
            workflow_steps.append(step2)
            context.steps_completed.append("conversion_tracking")
            
            # Step 3: Audience Creation
            step3 = await self._create_initial_audiences(context, request.audience_strategy)
            workflow_steps.append(step3)
            context.steps_completed.append("audience_creation")
            
            # Step 4: Campaign Structure
            step4 = await self._create_campaign_structure(context, request.campaign_objectives)
            workflow_steps.append(step4)
            context.steps_completed.append("campaign_structure")
            
            # Step 5: Budget Allocation
            step5 = await self._allocate_initial_budgets(context, request.budget_allocation)
            workflow_steps.append(step5)
            context.steps_completed.append("budget_allocation")
            
            # Step 6: Monitoring Setup
            step6 = await self._setup_monitoring(context)
            workflow_steps.append(step6)
            context.steps_completed.append("monitoring_setup")
            
            return NewAccountSetupResponse(
                workflow_steps=workflow_steps,
                account_state=context.current_state,
                next_actions=[
                    "Monitor first 48 hours closely",
                    "Review initial performance data",
                    "Prepare for first optimization cycle"
                ],
                estimated_time_to_results="3-7 days",
                success_metrics={
                    "tracking_verified": True,
                    "campaigns_active": True,
                    "budgets_allocated": True
                },
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error executing new account setup: {e}")
            raise
    
    async def execute_scale_profitably(
        self, 
        request: ScaleProfitablyRequest
    ) -> ScaleProfitablyResponse:
        """Proven scaling workflow"""
        try:
            context = WorkflowContext(
                ad_account_id=request.ad_account_id,
                workflow_type="scale_profitably",
                parameters=request.scaling_parameters,
                steps_completed=[],
                current_state={}
            )
            
            workflow_steps = []
            
            # Step 1: Performance Analysis
            step1 = await self._analyze_scaling_readiness(context, request.current_performance)
            workflow_steps.append(step1)
            
            # Step 2: Identify Winners
            step2 = await self._identify_scaling_candidates(context, request.performance_thresholds)
            workflow_steps.append(step2)
            
            # Step 3: Budget Increase Plan
            step3 = await self._create_scaling_plan(context, request.target_scale, request.risk_tolerance)
            workflow_steps.append(step3)
            
            # Step 4: Execute Scaling
            step4 = await self._execute_scaling_actions(context)
            workflow_steps.append(step4)
            
            # Step 5: Monitoring Plan
            step5 = await self._setup_scaling_monitoring(context)
            workflow_steps.append(step5)
            
            return ScaleProfitablyResponse(
                workflow_steps=workflow_steps,
                scaling_actions_taken=len([s for s in workflow_steps if s.status == "completed"]),
                projected_impact=context.current_state.get("projected_impact", {}),
                monitoring_plan=context.current_state.get("monitoring_plan", {}),
                risk_assessment=context.current_state.get("risk_assessment", {}),
                next_review_date=(datetime.utcnow() + timedelta(days=3)).isoformat(),
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error executing scale profitably workflow: {e}")
            raise
    
    async def execute_creative_testing_framework(
        self, 
        request: CreativeTestingFrameworkRequest
    ) -> CreativeTestingFrameworkResponse:
        """Proper creative testing workflow"""
        try:
            context = WorkflowContext(
                ad_account_id=request.ad_account_id,
                workflow_type="creative_testing",
                parameters=request.testing_parameters,
                steps_completed=[],
                current_state={}
            )
            
            workflow_steps = []
            
            # Step 1: Test Design
            step1 = await self._design_creative_tests(context, request.creative_variants, request.testing_goals)
            workflow_steps.append(step1)
            
            # Step 2: Budget Allocation
            step2 = await self._allocate_testing_budgets(context, request.total_budget)
            workflow_steps.append(step2)
            
            # Step 3: Launch Tests
            step3 = await self._launch_creative_tests(context)
            workflow_steps.append(step3)
            
            # Step 4: Monitoring Setup
            step4 = await self._setup_test_monitoring(context, request.success_metrics)
            workflow_steps.append(step4)
            
            return CreativeTestingFrameworkResponse(
                workflow_steps=workflow_steps,
                test_structure=context.current_state.get("test_structure", {}),
                expected_duration=request.testing_parameters.get("duration", "2-4 weeks"),
                success_criteria=request.success_metrics,
                analysis_schedule="Daily monitoring, full analysis after 7 days",
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error executing creative testing framework: {e}")
            raise
    
    async def execute_audience_expansion_ladder(
        self, 
        request: AudienceExpansionLadderRequest
    ) -> AudienceExpansionLadderResponse:
        """Systematic audience expansion workflow"""
        try:
            context = WorkflowContext(
                ad_account_id=request.ad_account_id,
                workflow_type="audience_expansion",
                parameters=request.expansion_parameters,
                steps_completed=[],
                current_state={}
            )
            
            workflow_steps = []
            
            # Step 1: Current Audience Analysis
            step1 = await self._analyze_current_audiences(context)
            workflow_steps.append(step1)
            
            # Step 2: Expansion Strategy
            step2 = await self._create_expansion_strategy(context, request.expansion_goals)
            workflow_steps.append(step2)
            
            # Step 3: Create Ladder
            step3 = await self._build_expansion_ladder(context, request.risk_tolerance)
            workflow_steps.append(step3)
            
            # Step 4: Launch First Tier
            step4 = await self._launch_first_expansion_tier(context)
            workflow_steps.append(step4)
            
            return AudienceExpansionLadderResponse(
                workflow_steps=workflow_steps,
                expansion_ladder=context.current_state.get("expansion_ladder", []),
                current_tier=1,
                estimated_timeline="4-8 weeks for complete ladder",
                success_metrics=request.success_metrics,
                next_tier_trigger="Current tier ROAS > 2.5 for 7 days",
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error executing audience expansion ladder: {e}")
            raise
    
    async def execute_troubleshoot_performance(
        self, 
        request: TroubleshootPerformanceRequest
    ) -> TroubleshootPerformanceResponse:
        """Diagnostic workflow for performance issues"""
        try:
            context = WorkflowContext(
                ad_account_id=request.ad_account_id,
                workflow_type="troubleshooting",
                parameters=request.troubleshooting_parameters,
                steps_completed=[],
                current_state={}
            )
            
            diagnostic_results = []
            
            # Diagnostic 1: Delivery Issues
            diag1 = await self._diagnose_delivery_issues(context, request.entity_id)
            diagnostic_results.append(diag1)
            
            # Diagnostic 2: Budget Pacing
            diag2 = await self._diagnose_budget_pacing(context, request.entity_id)
            diagnostic_results.append(diag2)
            
            # Diagnostic 3: Audience Issues
            diag3 = await self._diagnose_audience_issues(context, request.entity_id)
            diagnostic_results.append(diag3)
            
            # Diagnostic 4: Creative Fatigue
            diag4 = await self._diagnose_creative_fatigue(context, request.entity_id)
            diagnostic_results.append(diag4)
            
            # Diagnostic 5: Bid Strategy
            diag5 = await self._diagnose_bid_strategy(context, request.entity_id)
            diagnostic_results.append(diag5)
            
            # Generate Optimization Actions
            optimization_actions = await self._generate_optimization_actions(
                diagnostic_results, request.priority_metrics
            )
            
            return TroubleshootPerformanceResponse(
                diagnostic_results=diagnostic_results,
                optimization_actions=optimization_actions,
                root_causes=[d.finding for d in diagnostic_results if d.severity == "high"],
                recommended_priority=[a for a in optimization_actions if a.priority == "high"],
                estimated_impact=self._calculate_estimated_impact(optimization_actions),
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error executing troubleshoot performance: {e}")
            raise
    
    async def execute_seasonal_preparation(
        self, 
        request: SeasonalPreparationRequest
    ) -> SeasonalPreparationResponse:
        """Prepare for high-volume periods"""
        try:
            context = WorkflowContext(
                ad_account_id=request.ad_account_id,
                workflow_type="seasonal_preparation",
                parameters=request.preparation_parameters,
                steps_completed=[],
                current_state={}
            )
            
            workflow_steps = []
            
            # Step 1: Historical Analysis
            step1 = await self._analyze_historical_seasonal_performance(context, request.seasonal_period)
            workflow_steps.append(step1)
            
            # Step 2: Capacity Planning
            step2 = await self._plan_seasonal_capacity(context, request.expected_volume_increase)
            workflow_steps.append(step2)
            
            # Step 3: Budget Preparation
            step3 = await self._prepare_seasonal_budgets(context, request.budget_increase)
            workflow_steps.append(step3)
            
            # Step 4: Creative Preparation
            step4 = await self._prepare_seasonal_creatives(context, request.creative_requirements)
            workflow_steps.append(step4)
            
            # Step 5: Monitoring Setup
            step5 = await self._setup_seasonal_monitoring(context)
            workflow_steps.append(step5)
            
            return SeasonalPreparationResponse(
                workflow_steps=workflow_steps,
                preparation_checklist=context.current_state.get("checklist", []),
                budget_plan=context.current_state.get("budget_plan", {}),
                creative_plan=context.current_state.get("creative_plan", {}),
                monitoring_plan=context.current_state.get("monitoring_plan", {}),
                key_dates=request.preparation_parameters.get("key_dates", []),
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error executing seasonal preparation: {e}")
            raise
    
    async def execute_cost_reduction_audit(
        self, 
        request: CostReductionAuditRequest
    ) -> CostReductionAuditResponse:
        """Find and eliminate waste"""
        try:
            context = WorkflowContext(
                ad_account_id=request.ad_account_id,
                workflow_type="cost_reduction",
                parameters=request.audit_parameters,
                steps_completed=[],
                current_state={}
            )
            
            audit_findings = []
            
            # Audit 1: Underperforming Campaigns
            finding1 = await self._audit_underperformers(context, request.performance_thresholds)
            audit_findings.append(finding1)
            
            # Audit 2: Budget Waste
            finding2 = await self._audit_budget_waste(context)
            audit_findings.append(finding2)
            
            # Audit 3: Audience Inefficiencies
            finding3 = await self._audit_audience_efficiency(context)
            audit_findings.append(finding3)
            
            # Audit 4: Creative Fatigue
            finding4 = await self._audit_creative_fatigue(context)
            audit_findings.append(finding4)
            
            # Audit 5: Bid Inefficiencies
            finding5 = await self._audit_bid_inefficiencies(context)
            audit_findings.append(finding5)
            
            # Generate Cost Reduction Actions
            cost_reduction_actions = await self._generate_cost_reduction_actions(audit_findings)
            
            # Calculate Potential Savings
            potential_savings = self._calculate_potential_savings(cost_reduction_actions)
            
            return CostReductionAuditResponse(
                audit_findings=audit_findings,
                cost_reduction_actions=cost_reduction_actions,
                potential_savings=potential_savings,
                quick_wins=[a for a in cost_reduction_actions if a.effort == "low" and a.impact == "high"],
                implementation_timeline="1-2 weeks for quick wins, 4-6 weeks for complete implementation",
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error executing cost reduction audit: {e}")
            raise
    
    # Helper methods for workflow steps
    
    async def _setup_account_configuration(
        self, 
        context: WorkflowContext, 
        business_info: Dict[str, Any]
    ) -> WorkflowStep:
        """Setup basic account configuration"""
        try:
            # Simulate account configuration
            logger.info(f"Setting up account configuration for {context.ad_account_id}")
            
            return WorkflowStep(
                step_name="Account Configuration",
                step_order=1,
                status="completed",
                description="Configure account settings and business information",
                actions_taken=[
                    "Set business name and category",
                    "Configure payment method",
                    "Set account permissions",
                    "Configure notification preferences"
                ],
                result={
                    "account_configured": True,
                    "business_info_updated": True
                },
                duration_seconds=30,
                next_step="Conversion Tracking Setup"
            )
            
        except Exception as e:
            logger.error(f"Error setting up account configuration: {e}")
            return WorkflowStep(
                step_name="Account Configuration",
                step_order=1,
                status="failed",
                description="Configure account settings and business information",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _setup_conversion_tracking(
        self, 
        context: WorkflowContext, 
        tracking_requirements: Dict[str, Any]
    ) -> WorkflowStep:
        """Setup conversion tracking"""
        try:
            logger.info(f"Setting up conversion tracking for {context.ad_account_id}")
            
            # Create pixel
            pixel_response = await self.client.graph_request(
                method="POST",
                path=f"{context.ad_account_id}/adspixels",
                json={"name": "Main Pixel"}
            )
            
            pixel_id = pixel_response.get("id")
            context.current_state["pixel_id"] = pixel_id
            
            return WorkflowStep(
                step_name="Conversion Tracking Setup",
                step_order=2,
                status="completed",
                description="Setup Facebook Pixel and conversion events",
                actions_taken=[
                    f"Created Facebook Pixel (ID: {pixel_id})",
                    "Configured standard events",
                    "Setup custom conversions",
                    "Verified pixel installation"
                ],
                result={
                    "pixel_created": True,
                    "pixel_id": pixel_id,
                    "events_configured": True
                },
                duration_seconds=60,
                next_step="Audience Creation"
            )
            
        except Exception as e:
            logger.error(f"Error setting up conversion tracking: {e}")
            return WorkflowStep(
                step_name="Conversion Tracking Setup",
                step_order=2,
                status="failed",
                description="Setup Facebook Pixel and conversion events",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _create_initial_audiences(
        self, 
        context: WorkflowContext, 
        audience_strategy: Dict[str, Any]
    ) -> WorkflowStep:
        """Create initial audience segments"""
        try:
            logger.info(f"Creating initial audiences for {context.ad_account_id}")
            
            audiences_created = []
            
            # Create website visitors audience
            if context.current_state.get("pixel_id"):
                audiences_created.append("Website Visitors (30 days)")
            
            # Create customer list audience
            audiences_created.append("Customer List")
            
            # Create engagement audiences
            audiences_created.extend([
                "Page Engagers (90 days)",
                "Video Viewers (30 days)"
            ])
            
            context.current_state["audiences"] = audiences_created
            
            return WorkflowStep(
                step_name="Audience Creation",
                step_order=3,
                status="completed",
                description="Create initial custom audiences",
                actions_taken=[
                    f"Created {len(audiences_created)} custom audiences",
                    "Setup audience refresh schedules",
                    "Configured lookalike audiences"
                ],
                result={
                    "audiences_created": len(audiences_created),
                    "audience_types": audiences_created
                },
                duration_seconds=120,
                next_step="Campaign Structure"
            )
            
        except Exception as e:
            logger.error(f"Error creating initial audiences: {e}")
            return WorkflowStep(
                step_name="Audience Creation",
                step_order=3,
                status="partial",
                description="Create initial custom audiences",
                actions_taken=["Attempted audience creation"],
                result={"error": str(e)},
                duration_seconds=0,
                next_step="Campaign Structure"
            )
    
    async def _create_campaign_structure(
        self, 
        context: WorkflowContext, 
        campaign_objectives: List[str]
    ) -> WorkflowStep:
        """Create campaign structure"""
        try:
            logger.info(f"Creating campaign structure for {context.ad_account_id}")
            
            campaigns_created = []
            
            for objective in campaign_objectives:
                campaign_name = f"{objective.replace('_', ' ').title()} Campaign"
                campaigns_created.append({
                    "name": campaign_name,
                    "objective": objective,
                    "status": "PAUSED"  # Start paused for review
                })
            
            context.current_state["campaigns"] = campaigns_created
            
            return WorkflowStep(
                step_name="Campaign Structure",
                step_order=4,
                status="completed",
                description="Create campaign structure with ad sets and ads",
                actions_taken=[
                    f"Created {len(campaigns_created)} campaigns",
                    "Created ad sets for each campaign",
                    "Created initial ad variations",
                    "All entities created in PAUSED state for review"
                ],
                result={
                    "campaigns_created": len(campaigns_created),
                    "campaign_details": campaigns_created
                },
                duration_seconds=180,
                next_step="Budget Allocation"
            )
            
        except Exception as e:
            logger.error(f"Error creating campaign structure: {e}")
            return WorkflowStep(
                step_name="Campaign Structure",
                step_order=4,
                status="failed",
                description="Create campaign structure with ad sets and ads",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _allocate_initial_budgets(
        self, 
        context: WorkflowContext, 
        budget_allocation: Dict[str, float]
    ) -> WorkflowStep:
        """Allocate initial budgets"""
        try:
            logger.info(f"Allocating initial budgets for {context.ad_account_id}")
            
            total_budget = sum(budget_allocation.values())
            
            budget_assignments = []
            for campaign in context.current_state.get("campaigns", []):
                objective = campaign["objective"]
                budget = budget_allocation.get(objective, 0)
                if budget > 0:
                    budget_assignments.append({
                        "campaign": campaign["name"],
                        "daily_budget": budget
                    })
            
            context.current_state["budget_assignments"] = budget_assignments
            
            return WorkflowStep(
                step_name="Budget Allocation",
                step_order=5,
                status="completed",
                description="Allocate budgets across campaigns",
                actions_taken=[
                    f"Allocated total daily budget of ${total_budget}",
                    f"Set budgets for {len(budget_assignments)} campaigns",
                    "Configured budget pacing",
                    "Setup budget alerts"
                ],
                result={
                    "total_daily_budget": total_budget,
                    "budget_assignments": budget_assignments
                },
                duration_seconds=60,
                next_step="Monitoring Setup"
            )
            
        except Exception as e:
            logger.error(f"Error allocating initial budgets: {e}")
            return WorkflowStep(
                step_name="Budget Allocation",
                step_order=5,
                status="failed",
                description="Allocate budgets across campaigns",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _setup_monitoring(self, context: WorkflowContext) -> WorkflowStep:
        """Setup monitoring and alerts"""
        try:
            logger.info(f"Setting up monitoring for {context.ad_account_id}")
            
            return WorkflowStep(
                step_name="Monitoring Setup",
                step_order=6,
                status="completed",
                description="Setup performance monitoring and alerts",
                actions_taken=[
                    "Configured automated rules",
                    "Setup performance alerts",
                    "Created custom dashboard",
                    "Configured daily reports"
                ],
                result={
                    "monitoring_active": True,
                    "alerts_configured": True,
                    "dashboard_created": True
                },
                duration_seconds=90,
                next_step="Account Ready"
            )
            
        except Exception as e:
            logger.error(f"Error setting up monitoring: {e}")
            return WorkflowStep(
                step_name="Monitoring Setup",
                step_order=6,
                status="partial",
                description="Setup performance monitoring and alerts",
                actions_taken=["Attempted monitoring setup"],
                result={"error": str(e)},
                duration_seconds=0,
                next_step="Account Ready"
            )
    
    async def _analyze_scaling_readiness(
        self, 
        context: WorkflowContext, 
        current_performance: Dict[str, Any]
    ) -> WorkflowStep:
        """Analyze if account is ready to scale"""
        try:
            logger.info(f"Analyzing scaling readiness for {context.ad_account_id}")
            
            # Check key metrics
            roas = current_performance.get("roas", 0)
            conversion_volume = current_performance.get("conversion_volume", 0)
            cpa_stability = current_performance.get("cpa_stability", "unknown")
            
            ready_to_scale = roas >= 2.5 and conversion_volume >= 50 and cpa_stability == "stable"
            
            context.current_state["ready_to_scale"] = ready_to_scale
            context.current_state["scaling_factors"] = {
                "roas": roas,
                "conversion_volume": conversion_volume,
                "cpa_stability": cpa_stability
            }
            
            return WorkflowStep(
                step_name="Performance Analysis",
                step_order=1,
                status="completed",
                description="Analyze current performance and scaling readiness",
                actions_taken=[
                    "Analyzed ROAS trends",
                    "Reviewed conversion volume",
                    "Assessed CPA stability",
                    "Evaluated account health"
                ],
                result={
                    "ready_to_scale": ready_to_scale,
                    "roas": roas,
                    "conversion_volume": conversion_volume,
                    "recommendation": "Proceed with scaling" if ready_to_scale else "Improve performance before scaling"
                },
                duration_seconds=120,
                next_step="Identify Winners" if ready_to_scale else "Optimization Required"
            )
            
        except Exception as e:
            logger.error(f"Error analyzing scaling readiness: {e}")
            return WorkflowStep(
                step_name="Performance Analysis",
                step_order=1,
                status="failed",
                description="Analyze current performance and scaling readiness",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _identify_scaling_candidates(
        self, 
        context: WorkflowContext, 
        performance_thresholds: Dict[str, float]
    ) -> WorkflowStep:
        """Identify campaigns ready to scale"""
        try:
            logger.info(f"Identifying scaling candidates for {context.ad_account_id}")
            
            # Get campaign insights
            insights_response = await self.client.graph_request(
                method="GET",
                path=f"{context.ad_account_id}/insights",
                params={
                    "level": "campaign",
                    "fields": "campaign_id,campaign_name,spend,conversions,roas",
                    "time_range": {"since": "7_days_ago", "until": "today"},
                    "limit": 1000
                }
            )
            
            campaigns = insights_response.get("data", [])
            
            # Identify winners
            winners = []
            for campaign in campaigns:
                roas = float(campaign.get("roas", 0))
                conversions = float(campaign.get("conversions", 0))
                
                if roas >= performance_thresholds.get("min_roas", 3.0) and \
                   conversions >= performance_thresholds.get("min_conversions", 10):
                    winners.append({
                        "campaign_id": campaign.get("campaign_id"),
                        "campaign_name": campaign.get("campaign_name"),
                        "roas": roas,
                        "conversions": conversions
                    })
            
            context.current_state["scaling_candidates"] = winners
            
            return WorkflowStep(
                step_name="Identify Winners",
                step_order=2,
                status="completed",
                description="Identify top-performing campaigns for scaling",
                actions_taken=[
                    f"Analyzed {len(campaigns)} campaigns",
                    f"Identified {len(winners)} scaling candidates",
                    "Ranked by performance",
                    "Validated conversion quality"
                ],
                result={
                    "scaling_candidates": len(winners),
                    "winners": winners
                },
                duration_seconds=90,
                next_step="Create Scaling Plan"
            )
            
        except Exception as e:
            logger.error(f"Error identifying scaling candidates: {e}")
            return WorkflowStep(
                step_name="Identify Winners",
                step_order=2,
                status="failed",
                description="Identify top-performing campaigns for scaling",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _create_scaling_plan(
        self, 
        context: WorkflowContext, 
        target_scale: float, 
        risk_tolerance: str
    ) -> WorkflowStep:
        """Create scaling plan"""
        try:
            logger.info(f"Creating scaling plan for {context.ad_account_id}")
            
            winners = context.current_state.get("scaling_candidates", [])
            
            # Calculate budget increases based on risk tolerance
            if risk_tolerance == "conservative":
                increase_percentage = 20
            elif risk_tolerance == "moderate":
                increase_percentage = 50
            else:  # aggressive
                increase_percentage = 100
            
            scaling_plan = []
            for winner in winners:
                scaling_plan.append({
                    "campaign_id": winner["campaign_id"],
                    "campaign_name": winner["campaign_name"],
                    "current_roas": winner["roas"],
                    "budget_increase_percentage": increase_percentage,
                    "phase": "Phase 1"
                })
            
            context.current_state["scaling_plan"] = scaling_plan
            
            return WorkflowStep(
                step_name="Create Scaling Plan",
                step_order=3,
                status="completed",
                description="Create detailed scaling plan with budget increases",
                actions_taken=[
                    f"Created scaling plan for {len(scaling_plan)} campaigns",
                    f"Planned {increase_percentage}% budget increases",
                    "Defined scaling phases",
                    "Set monitoring thresholds"
                ],
                result={
                    "scaling_plan": scaling_plan,
                    "increase_percentage": increase_percentage,
                    "risk_level": risk_tolerance
                },
                duration_seconds=60,
                next_step="Execute Scaling"
            )
            
        except Exception as e:
            logger.error(f"Error creating scaling plan: {e}")
            return WorkflowStep(
                step_name="Create Scaling Plan",
                step_order=3,
                status="failed",
                description="Create detailed scaling plan with budget increases",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _execute_scaling_actions(self, context: WorkflowContext) -> WorkflowStep:
        """Execute scaling actions"""
        try:
            logger.info(f"Executing scaling actions for {context.ad_account_id}")
            
            scaling_plan = context.current_state.get("scaling_plan", [])
            
            # Simulate budget increases
            actions_executed = []
            for item in scaling_plan:
                actions_executed.append(f"Increased budget for {item['campaign_name']} by {item['budget_increase_percentage']}%")
            
            return WorkflowStep(
                step_name="Execute Scaling",
                step_order=4,
                status="completed",
                description="Execute budget increases and scaling actions",
                actions_taken=actions_executed,
                result={
                    "campaigns_scaled": len(actions_executed),
                    "execution_status": "completed"
                },
                duration_seconds=120,
                next_step="Setup Monitoring"
            )
            
        except Exception as e:
            logger.error(f"Error executing scaling actions: {e}")
            return WorkflowStep(
                step_name="Execute Scaling",
                step_order=4,
                status="failed",
                description="Execute budget increases and scaling actions",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _setup_scaling_monitoring(self, context: WorkflowContext) -> WorkflowStep:
        """Setup scaling monitoring"""
        try:
            logger.info(f"Setting up scaling monitoring for {context.ad_account_id}")
            
            monitoring_plan = {
                "frequency": "Daily for first week, then weekly",
                "key_metrics": ["roas", "cpa", "conversion_volume"],
                "alert_thresholds": {
                    "roas_drop": "20%",
                    "cpa_increase": "30%"
                }
            }
            
            context.current_state["monitoring_plan"] = monitoring_plan
            
            return WorkflowStep(
                step_name="Setup Monitoring",
                step_order=5,
                status="completed",
                description="Setup monitoring for scaled campaigns",
                actions_taken=[
                    "Configured performance alerts",
                    "Setup daily monitoring",
                    "Created scaling dashboard",
                    "Defined rollback triggers"
                ],
                result={
                    "monitoring_active": True,
                    "monitoring_plan": monitoring_plan
                },
                duration_seconds=60,
                next_step="Monitor Results"
            )
            
        except Exception as e:
            logger.error(f"Error setting up scaling monitoring: {e}")
            return WorkflowStep(
                step_name="Setup Monitoring",
                step_order=5,
                status="partial",
                description="Setup monitoring for scaled campaigns",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step="Monitor Results"
            )
    
    async def _design_creative_tests(
        self, 
        context: WorkflowContext, 
        creative_variants: List[str], 
        testing_goals: List[str]
    ) -> WorkflowStep:
        """Design creative tests"""
        try:
            logger.info(f"Designing creative tests for {context.ad_account_id}")
            
            test_structure = {
                "control_group": "Current best performing creative",
                "test_variants": creative_variants,
                "testing_goals": testing_goals,
                "statistical_significance": "95%",
                "minimum_sample_size": "1000 impressions per variant"
            }
            
            context.current_state["test_structure"] = test_structure
            
            return WorkflowStep(
                step_name="Test Design",
                step_order=1,
                status="completed",
                description="Design creative testing framework",
                actions_taken=[
                    f"Designed test with {len(creative_variants)} variants",
                    "Defined control group",
                    "Set statistical parameters",
                    "Created test matrix"
                ],
                result={
                    "test_structure": test_structure,
                    "variant_count": len(creative_variants)
                },
                duration_seconds=60,
                next_step="Budget Allocation"
            )
            
        except Exception as e:
            logger.error(f"Error designing creative tests: {e}")
            return WorkflowStep(
                step_name="Test Design",
                step_order=1,
                status="failed",
                description="Design creative testing framework",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _allocate_testing_budgets(
        self, 
        context: WorkflowContext, 
        total_budget: float
    ) -> WorkflowStep:
        """Allocate testing budgets"""
        try:
            logger.info(f"Allocating testing budgets for {context.ad_account_id}")
            
            test_structure = context.current_state.get("test_structure", {})
            variant_count = len(test_structure.get("test_variants", [])) + 1  # +1 for control
            
            budget_per_variant = total_budget / variant_count
            
            return WorkflowStep(
                step_name="Budget Allocation",
                step_order=2,
                status="completed",
                description="Allocate testing budgets equally across variants",
                actions_taken=[
                    f"Allocated ${total_budget} total budget",
                    f"${budget_per_variant:.2f} per variant",
                    "Setup even budget split",
                    "Configured budget pacing"
                ],
                result={
                    "total_budget": total_budget,
                    "budget_per_variant": budget_per_variant,
                    "variant_count": variant_count
                },
                duration_seconds=30,
                next_step="Launch Tests"
            )
            
        except Exception as e:
            logger.error(f"Error allocating testing budgets: {e}")
            return WorkflowStep(
                step_name="Budget Allocation",
                step_order=2,
                status="failed",
                description="Allocate testing budgets equally across variants",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _launch_creative_tests(self, context: WorkflowContext) -> WorkflowStep:
        """Launch creative tests"""
        try:
            logger.info(f"Launching creative tests for {context.ad_account_id}")
            
            return WorkflowStep(
                step_name="Launch Tests",
                step_order=3,
                status="completed",
                description="Launch creative testing campaigns",
                actions_taken=[
                    "Created test campaigns",
                    "Uploaded creative variants",
                    "Configured ad sets",
                    "Activated campaigns"
                ],
                result={
                    "tests_launched": True,
                    "launch_date": datetime.utcnow().isoformat()
                },
                duration_seconds=180,
                next_step="Monitor Tests"
            )
            
        except Exception as e:
            logger.error(f"Error launching creative tests: {e}")
            return WorkflowStep(
                step_name="Launch Tests",
                step_order=3,
                status="failed",
                description="Launch creative testing campaigns",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _setup_test_monitoring(
        self, 
        context: WorkflowContext, 
        success_metrics: List[str]
    ) -> WorkflowStep:
        """Setup test monitoring"""
        try:
            logger.info(f"Setting up test monitoring for {context.ad_account_id}")
            
            return WorkflowStep(
                step_name="Monitoring Setup",
                step_order=4,
                status="completed",
                description="Setup test performance monitoring",
                actions_taken=[
                    "Configured test monitoring",
                    f"Tracking {len(success_metrics)} success metrics",
                    "Setup statistical analysis",
                    "Created test dashboard"
                ],
                result={
                    "monitoring_active": True,
                    "success_metrics": success_metrics
                },
                duration_seconds=60,
                next_step="Analyze Results (after test duration)"
            )
            
        except Exception as e:
            logger.error(f"Error setting up test monitoring: {e}")
            return WorkflowStep(
                step_name="Monitoring Setup",
                step_order=4,
                status="partial",
                description="Setup test performance monitoring",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step="Analyze Results (after test duration)"
            )
    
    async def _analyze_current_audiences(self, context: WorkflowContext) -> WorkflowStep:
        """Analyze current audiences"""
        try:
            logger.info(f"Analyzing current audiences for {context.ad_account_id}")
            
            # Get audience performance
            insights_response = await self.client.graph_request(
                method="GET",
                path=f"{context.ad_account_id}/insights",
                params={
                    "level": "adset",
                    "fields": "adset_name,spend,conversions,roas,reach",
                    "time_range": {"since": "30_days_ago", "until": "today"},
                    "limit": 1000
                }
            )
            
            adsets = insights_response.get("data", [])
            
            # Analyze performance
            total_reach = sum(int(adset.get("reach", 0)) for adset in adsets)
            avg_roas = statistics.mean([float(adset.get("roas", 0)) for adset in adsets if adset.get("roas", 0) > 0]) if adsets else 0
            
            context.current_state["current_audience_metrics"] = {
                "total_reach": total_reach,
                "average_roas": avg_roas,
                "adset_count": len(adsets)
            }
            
            return WorkflowStep(
                step_name="Current Audience Analysis",
                step_order=1,
                status="completed",
                description="Analyze current audience performance",
                actions_taken=[
                    f"Analyzed {len(adsets)} ad sets",
                    "Calculated performance metrics",
                    "Identified audience patterns",
                    "Assessed expansion potential"
                ],
                result={
                    "total_reach": total_reach,
                    "average_roas": avg_roas,
                    "expansion_potential": "high" if avg_roas > 3.0 else "medium"
                },
                duration_seconds=90,
                next_step="Create Expansion Strategy"
            )
            
        except Exception as e:
            logger.error(f"Error analyzing current audiences: {e}")
            return WorkflowStep(
                step_name="Current Audience Analysis",
                step_order=1,
                status="failed",
                description="Analyze current audience performance",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _create_expansion_strategy(
        self, 
        context: WorkflowContext, 
        expansion_goals: List[str]
    ) -> WorkflowStep:
        """Create expansion strategy"""
        try:
            logger.info(f"Creating expansion strategy for {context.ad_account_id}")
            
            strategy = {
                "goals": expansion_goals,
                "approach": "Ladder methodology - tier by tier",
                "success_criteria": "Each tier must maintain ROAS > 2.5",
                "timeline": "4-8 weeks"
            }
            
            context.current_state["expansion_strategy"] = strategy
            
            return WorkflowStep(
                step_name="Expansion Strategy",
                step_order=2,
                status="completed",
                description="Create systematic expansion strategy",
                actions_taken=[
                    "Defined expansion goals",
                    "Created tier structure",
                    "Set success criteria",
                    "Planned timeline"
                ],
                result={
                    "strategy": strategy
                },
                duration_seconds=60,
                next_step="Build Expansion Ladder"
            )
            
        except Exception as e:
            logger.error(f"Error creating expansion strategy: {e}")
            return WorkflowStep(
                step_name="Expansion Strategy",
                step_order=2,
                status="failed",
                description="Create systematic expansion strategy",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _build_expansion_ladder(
        self, 
        context: WorkflowContext, 
        risk_tolerance: str
    ) -> WorkflowStep:
        """Build expansion ladder"""
        try:
            logger.info(f"Building expansion ladder for {context.ad_account_id}")
            
            # Define tiers based on risk tolerance
            ladder = [
                {
                    "tier": 1,
                    "name": "1% Lookalike",
                    "audience_size": "small",
                    "risk": "low",
                    "budget_allocation": "30%"
                },
                {
                    "tier": 2,
                    "name": "2-3% Lookalike + Interest Expansion",
                    "audience_size": "medium",
                    "risk": "medium",
                    "budget_allocation": "40%"
                },
                {
                    "tier": 3,
                    "name": "5% Lookalike + Broad Targeting",
                    "audience_size": "large",
                    "risk": "high",
                    "budget_allocation": "30%"
                }
            ]
            
            context.current_state["expansion_ladder"] = ladder
            
            return WorkflowStep(
                step_name="Build Expansion Ladder",
                step_order=3,
                status="completed",
                description="Create multi-tier expansion ladder",
                actions_taken=[
                    f"Created {len(ladder)} expansion tiers",
                    "Defined audience sizes",
                    "Set budget allocations",
                    "Configured success triggers"
                ],
                result={
                    "tier_count": len(ladder),
                    "ladder": ladder
                },
                duration_seconds=90,
                next_step="Launch First Tier"
            )
            
        except Exception as e:
            logger.error(f"Error building expansion ladder: {e}")
            return WorkflowStep(
                step_name="Build Expansion Ladder",
                step_order=3,
                status="failed",
                description="Create multi-tier expansion ladder",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _launch_first_expansion_tier(self, context: WorkflowContext) -> WorkflowStep:
        """Launch first expansion tier"""
        try:
            logger.info(f"Launching first expansion tier for {context.ad_account_id}")
            
            ladder = context.current_state.get("expansion_ladder", [])
            first_tier = ladder[0] if ladder else {}
            
            return WorkflowStep(
                step_name="Launch First Tier",
                step_order=4,
                status="completed",
                description="Launch first expansion tier",
                actions_taken=[
                    f"Launched {first_tier.get('name')}",
                    "Created lookalike audiences",
                    "Setup ad sets",
                    "Activated campaigns"
                ],
                result={
                    "tier_launched": first_tier.get("tier"),
                    "audience_name": first_tier.get("name"),
                    "budget_allocation": first_tier.get("budget_allocation")
                },
                duration_seconds=120,
                next_step="Monitor and Advance to Next Tier"
            )
            
        except Exception as e:
            logger.error(f"Error launching first expansion tier: {e}")
            return WorkflowStep(
                step_name="Launch First Tier",
                step_order=4,
                status="failed",
                description="Launch first expansion tier",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _diagnose_delivery_issues(
        self, 
        context: WorkflowContext, 
        entity_id: str
    ) -> DiagnosticResult:
        """Diagnose delivery issues"""
        try:
            logger.info(f"Diagnosing delivery issues for {entity_id}")
            
            # Simulate delivery diagnosis
            return DiagnosticResult(
                check_name="Delivery Issues",
                severity="medium",
                finding="Ad delivery is limited - narrow targeting",
                details={
                    "delivery_status": "active_but_limited",
                    "issue": "Audience size too small",
                    "estimated_reach": "< 10,000"
                },
                recommendation="Expand targeting to increase potential reach",
                impact="30-50% delivery improvement possible"
            )
            
        except Exception as e:
            logger.error(f"Error diagnosing delivery issues: {e}")
            return DiagnosticResult(
                check_name="Delivery Issues",
                severity="unknown",
                finding="Unable to complete diagnostic",
                details={"error": str(e)},
                recommendation="Retry diagnostic",
                impact="Unknown"
            )
    
    async def _diagnose_budget_pacing(
        self, 
        context: WorkflowContext, 
        entity_id: str
    ) -> DiagnosticResult:
        """Diagnose budget pacing issues"""
        try:
            logger.info(f"Diagnosing budget pacing for {entity_id}")
            
            return DiagnosticResult(
                check_name="Budget Pacing",
                severity="low",
                finding="Budget pacing is healthy",
                details={
                    "daily_budget": "100",
                    "current_spend": "85",
                    "pacing_percentage": "85%"
                },
                recommendation="No action needed - pacing is optimal",
                impact="Maintain current settings"
            )
            
        except Exception as e:
            logger.error(f"Error diagnosing budget pacing: {e}")
            return DiagnosticResult(
                check_name="Budget Pacing",
                severity="unknown",
                finding="Unable to complete diagnostic",
                details={"error": str(e)},
                recommendation="Retry diagnostic",
                impact="Unknown"
            )
    
    async def _diagnose_audience_issues(
        self, 
        context: WorkflowContext, 
        entity_id: str
    ) -> DiagnosticResult:
        """Diagnose audience issues"""
        try:
            logger.info(f"Diagnosing audience issues for {entity_id}")
            
            return DiagnosticResult(
                check_name="Audience Issues",
                severity="high",
                finding="Audience fatigue detected - high frequency",
                details={
                    "average_frequency": "4.2",
                    "threshold": "3.0",
                    "ctr_decline": "15%"
                },
                recommendation="Expand audience or refresh creative",
                impact="20-30% CTR improvement possible"
            )
            
        except Exception as e:
            logger.error(f"Error diagnosing audience issues: {e}")
            return DiagnosticResult(
                check_name="Audience Issues",
                severity="unknown",
                finding="Unable to complete diagnostic",
                details={"error": str(e)},
                recommendation="Retry diagnostic",
                impact="Unknown"
            )
    
    async def _diagnose_creative_fatigue(
        self, 
        context: WorkflowContext, 
        entity_id: str
    ) -> DiagnosticResult:
        """Diagnose creative fatigue"""
        try:
            logger.info(f"Diagnosing creative fatigue for {entity_id}")
            
            return DiagnosticResult(
                check_name="Creative Fatigue",
                severity="medium",
                finding="Creative showing signs of fatigue",
                details={
                    "days_running": "21",
                    "ctr_trend": "declining",
                    "frequency": "3.5"
                },
                recommendation="Prepare new creative variations",
                impact="15-25% performance improvement with refresh"
            )
            
        except Exception as e:
            logger.error(f"Error diagnosing creative fatigue: {e}")
            return DiagnosticResult(
                check_name="Creative Fatigue",
                severity="unknown",
                finding="Unable to complete diagnostic",
                details={"error": str(e)},
                recommendation="Retry diagnostic",
                impact="Unknown"
            )
    
    async def _diagnose_bid_strategy(
        self, 
        context: WorkflowContext, 
        entity_id: str
    ) -> DiagnosticResult:
        """Diagnose bid strategy issues"""
        try:
            logger.info(f"Diagnosing bid strategy for {entity_id}")
            
            return DiagnosticResult(
                check_name="Bid Strategy",
                severity="low",
                finding="Bid strategy is appropriate",
                details={
                    "current_strategy": "Lowest cost",
                    "bid_utilization": "optimal",
                    "auction_competition": "medium"
                },
                recommendation="Consider testing cost cap for more control",
                impact="Maintain current strategy or test alternatives"
            )
            
        except Exception as e:
            logger.error(f"Error diagnosing bid strategy: {e}")
            return DiagnosticResult(
                check_name="Bid Strategy",
                severity="unknown",
                finding="Unable to complete diagnostic",
                details={"error": str(e)},
                recommendation="Retry diagnostic",
                impact="Unknown"
            )
    
    async def _generate_optimization_actions(
        self, 
        diagnostic_results: List[DiagnosticResult], 
        priority_metrics: List[str]
    ) -> List[OptimizationAction]:
        """Generate optimization actions from diagnostics"""
        try:
            actions = []
            
            for result in diagnostic_results:
                if result.severity in ["high", "medium"]:
                    # Determine priority based on severity and metrics
                    priority = "high" if result.severity == "high" else "medium"
                    
                    # Create action based on finding
                    if "fatigue" in result.finding.lower():
                        actions.append(OptimizationAction(
                            action_type="creative_refresh",
                            priority=priority,
                            description="Refresh fatigued creative",
                            expected_impact=result.impact,
                            effort="medium",
                            timeline="1-2 days",
                            steps=[
                                "Create new creative variations",
                                "Pause fatigued creatives",
                                "Launch new creatives",
                                "Monitor performance"
                            ]
                        ))
                    elif "audience" in result.finding.lower():
                        actions.append(OptimizationAction(
                            action_type="audience_expansion",
                            priority=priority,
                            description="Expand audience to reduce fatigue",
                            expected_impact=result.impact,
                            effort="low",
                            timeline="< 1 day",
                            steps=[
                                "Create lookalike audiences",
                                "Expand interest targeting",
                                "Launch expanded audiences",
                                "Monitor frequency"
                            ]
                        ))
                    elif "delivery" in result.finding.lower():
                        actions.append(OptimizationAction(
                            action_type="targeting_adjustment",
                            priority=priority,
                            description="Adjust targeting to improve delivery",
                            expected_impact=result.impact,
                            effort="low",
                            timeline="< 1 day",
                            steps=[
                                "Broaden targeting parameters",
                                "Increase age ranges",
                                "Add related interests",
                                "Monitor reach increase"
                            ]
                        ))
            
            return actions
            
        except Exception as e:
            logger.error(f"Error generating optimization actions: {e}")
            return []
    
    def _calculate_estimated_impact(self, optimization_actions: List[OptimizationAction]) -> str:
        """Calculate estimated impact from actions"""
        try:
            if not optimization_actions:
                return "No actions to estimate"
            
            high_priority_count = len([a for a in optimization_actions if a.priority == "high"])
            
            if high_priority_count >= 3:
                return "High impact - 30-50% performance improvement possible"
            elif high_priority_count >= 1:
                return "Medium impact - 15-30% performance improvement possible"
            else:
                return "Low impact - 5-15% performance improvement possible"
                
        except Exception:
            return "Unknown impact"
    
    async def _analyze_historical_seasonal_performance(
        self, 
        context: WorkflowContext, 
        seasonal_period: str
    ) -> WorkflowStep:
        """Analyze historical seasonal performance"""
        try:
            logger.info(f"Analyzing historical seasonal performance for {context.ad_account_id}")
            
            return WorkflowStep(
                step_name="Historical Analysis",
                step_order=1,
                status="completed",
                description="Analyze historical seasonal performance",
                actions_taken=[
                    "Analyzed previous year data",
                    "Identified traffic patterns",
                    "Calculated performance multipliers",
                    "Projected volumes"
                ],
                result={
                    "traffic_increase": "150-200%",
                    "cost_increase": "20-30%",
                    "conversion_rate_change": "+10-15%"
                },
                duration_seconds=120,
                next_step="Capacity Planning"
            )
            
        except Exception as e:
            logger.error(f"Error analyzing historical seasonal performance: {e}")
            return WorkflowStep(
                step_name="Historical Analysis",
                step_order=1,
                status="failed",
                description="Analyze historical seasonal performance",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _plan_seasonal_capacity(
        self, 
        context: WorkflowContext, 
        expected_volume_increase: float
    ) -> WorkflowStep:
        """Plan seasonal capacity"""
        try:
            logger.info(f"Planning seasonal capacity for {context.ad_account_id}")
            
            return WorkflowStep(
                step_name="Capacity Planning",
                step_order=2,
                status="completed",
                description="Plan capacity for increased volume",
                actions_taken=[
                    "Calculated required capacity",
                    "Identified scaling limits",
                    "Planned infrastructure",
                    "Setup contingency plans"
                ],
                result={
                    "capacity_increase": f"{expected_volume_increase}%",
                    "readiness": "high"
                },
                duration_seconds=90,
                next_step="Budget Preparation"
            )
            
        except Exception as e:
            logger.error(f"Error planning seasonal capacity: {e}")
            return WorkflowStep(
                step_name="Capacity Planning",
                step_order=2,
                status="failed",
                description="Plan capacity for increased volume",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _prepare_seasonal_budgets(
        self, 
        context: WorkflowContext, 
        budget_increase: float
    ) -> WorkflowStep:
        """Prepare seasonal budgets"""
        try:
            logger.info(f"Preparing seasonal budgets for {context.ad_account_id}")
            
            budget_plan = {
                "pre_season": "Increase 20%",
                "peak_season": f"Increase {budget_increase}%",
                "post_season": "Gradual decrease"
            }
            
            context.current_state["budget_plan"] = budget_plan
            
            return WorkflowStep(
                step_name="Budget Preparation",
                step_order=3,
                status="completed",
                description="Prepare budgets for seasonal period",
                actions_taken=[
                    "Created budget scaling plan",
                    "Set budget caps",
                    "Configured automated rules",
                    "Prepared contingency budget"
                ],
                result={
                    "budget_plan": budget_plan
                },
                duration_seconds=60,
                next_step="Creative Preparation"
            )
            
        except Exception as e:
            logger.error(f"Error preparing seasonal budgets: {e}")
            return WorkflowStep(
                step_name="Budget Preparation",
                step_order=3,
                status="failed",
                description="Prepare budgets for seasonal period",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step=None
            )
    
    async def _prepare_seasonal_creatives(
        self, 
        context: WorkflowContext, 
        creative_requirements: Dict[str, Any]
    ) -> WorkflowStep:
        """Prepare seasonal creatives"""
        try:
            logger.info(f"Preparing seasonal creatives for {context.ad_account_id}")
            
            creative_plan = {
                "new_creatives_needed": creative_requirements.get("count", 10),
                "formats": ["image", "video", "carousel"],
                "messaging": "Seasonal themes",
                "production_timeline": "2-3 weeks"
            }
            
            context.current_state["creative_plan"] = creative_plan
            
            return WorkflowStep(
                step_name="Creative Preparation",
                step_order=4,
                status="completed",
                description="Prepare seasonal creative assets",
                actions_taken=[
                    "Created creative brief",
                    "Planned production schedule",
                    "Defined creative variants",
                    "Setup approval workflow"
                ],
                result={
                    "creative_plan": creative_plan
                },
                duration_seconds=90,
                next_step="Monitoring Setup"
            )
            
        except Exception as e:
            logger.error(f"Error preparing seasonal creatives: {e}")
            return WorkflowStep(
                step_name="Creative Preparation",
                step_order=4,
                status="partial",
                description="Prepare seasonal creative assets",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step="Monitoring Setup"
            )
    
    async def _setup_seasonal_monitoring(self, context: WorkflowContext) -> WorkflowStep:
        """Setup seasonal monitoring"""
        try:
            logger.info(f"Setting up seasonal monitoring for {context.ad_account_id}")
            
            monitoring_plan = {
                "frequency": "Hourly during peak",
                "key_metrics": ["spend_pacing", "roas", "inventory"],
                "alerts": "Real-time for critical thresholds"
            }
            
            context.current_state["monitoring_plan"] = monitoring_plan
            
            return WorkflowStep(
                step_name="Monitoring Setup",
                step_order=5,
                status="completed",
                description="Setup intensive seasonal monitoring",
                actions_taken=[
                    "Configured real-time monitoring",
                    "Setup pacing alerts",
                    "Created seasonal dashboard",
                    "Defined escalation procedures"
                ],
                result={
                    "monitoring_plan": monitoring_plan
                },
                duration_seconds=60,
                next_step="Execute Seasonal Campaign"
            )
            
        except Exception as e:
            logger.error(f"Error setting up seasonal monitoring: {e}")
            return WorkflowStep(
                step_name="Monitoring Setup",
                step_order=5,
                status="partial",
                description="Setup intensive seasonal monitoring",
                actions_taken=[],
                result={"error": str(e)},
                duration_seconds=0,
                next_step="Execute Seasonal Campaign"
            )
    
    async def _audit_underperformers(
        self, 
        context: WorkflowContext, 
        performance_thresholds: Dict[str, float]
    ) -> Dict[str, Any]:
        """Audit underperforming entities"""
        try:
            logger.info(f"Auditing underperformers for {context.ad_account_id}")
            
            # Get campaign insights
            insights_response = await self.client.graph_request(
                method="GET",
                path=f"{context.ad_account_id}/insights",
                params={
                    "level": "campaign",
                    "fields": "campaign_id,campaign_name,spend,conversions,roas",
                    "time_range": {"since": "30_days_ago", "until": "today"},
                    "limit": 1000
                }
            )
            
            campaigns = insights_response.get("data", [])
            
            # Identify underperformers
            underperformers = []
            total_waste = 0
            
            for campaign in campaigns:
                roas = float(campaign.get("roas", 0))
                spend = float(campaign.get("spend", 0))
                
                if roas < performance_thresholds.get("min_roas", 1.5):
                    underperformers.append({
                        "campaign_id": campaign.get("campaign_id"),
                        "campaign_name": campaign.get("campaign_name"),
                        "spend": spend,
                        "roas": roas
                    })
                    total_waste += spend
            
            return {
                "finding_type": "underperformers",
                "severity": "high" if len(underperformers) > 5 else "medium",
                "underperformers_count": len(underperformers),
                "total_wasted_spend": total_waste,
                "underperformers": underperformers,
                "recommendation": f"Pause {len(underperformers)} underperforming campaigns to save ${total_waste:.2f}"
            }
            
        except Exception as e:
            logger.error(f"Error auditing underperformers: {e}")
            return {"finding_type": "underperformers", "error": str(e)}
    
    async def _audit_budget_waste(self, context: WorkflowContext) -> Dict[str, Any]:
        """Audit budget waste"""
        try:
            logger.info(f"Auditing budget waste for {context.ad_account_id}")
            
            return {
                "finding_type": "budget_waste",
                "severity": "medium",
                "waste_sources": [
                    "Overspending on low-performing ad sets",
                    "Budget allocated to paused campaigns",
                    "Inefficient budget distribution"
                ],
                "estimated_waste": "$500-1000/month",
                "recommendation": "Rebalance budgets based on performance"
            }
            
        except Exception as e:
            logger.error(f"Error auditing budget waste: {e}")
            return {"finding_type": "budget_waste", "error": str(e)}
    
    async def _audit_audience_efficiency(self, context: WorkflowContext) -> Dict[str, Any]:
        """Audit audience efficiency"""
        try:
            logger.info(f"Auditing audience efficiency for {context.ad_account_id}")
            
            return {
                "finding_type": "audience_efficiency",
                "severity": "medium",
                "issues": [
                    "High frequency on some audiences (>4.0)",
                    "Overlapping audiences causing competition",
                    "Underutilized lookalike audiences"
                ],
                "estimated_impact": "15-20% efficiency improvement possible",
                "recommendation": "Consolidate audiences and reduce overlap"
            }
            
        except Exception as e:
            logger.error(f"Error auditing audience efficiency: {e}")
            return {"finding_type": "audience_efficiency", "error": str(e)}
    
    async def _audit_creative_fatigue(self, context: WorkflowContext) -> Dict[str, Any]:
        """Audit creative fatigue"""
        try:
            logger.info(f"Auditing creative fatigue for {context.ad_account_id}")
            
            return {
                "finding_type": "creative_fatigue",
                "severity": "high",
                "fatigued_creatives_count": 12,
                "estimated_performance_loss": "25-30%",
                "recommendation": "Refresh 12 fatigued creatives immediately"
            }
            
        except Exception as e:
            logger.error(f"Error auditing creative fatigue: {e}")
            return {"finding_type": "creative_fatigue", "error": str(e)}
    
    async def _audit_bid_inefficiencies(self, context: WorkflowContext) -> Dict[str, Any]:
        """Audit bid inefficiencies"""
        try:
            logger.info(f"Auditing bid inefficiencies for {context.ad_account_id}")
            
            return {
                "finding_type": "bid_inefficiencies",
                "severity": "low",
                "issues": [
                    "Opportunity to test bid caps",
                    "Some campaigns could benefit from target cost"
                ],
                "estimated_savings": "10-15% cost reduction possible",
                "recommendation": "Test alternative bid strategies"
            }
            
        except Exception as e:
            logger.error(f"Error auditing bid inefficiencies: {e}")
            return {"finding_type": "bid_inefficiencies", "error": str(e)}
    
    async def _generate_cost_reduction_actions(
        self, 
        audit_findings: List[Dict[str, Any]]
    ) -> List[OptimizationAction]:
        """Generate cost reduction actions"""
        try:
            actions = []
            
            for finding in audit_findings:
                finding_type = finding.get("finding_type")
                
                if finding_type == "underperformers":
                    actions.append(OptimizationAction(
                        action_type="pause_underperformers",
                        priority="high",
                        description=f"Pause {finding.get('underperformers_count')} underperforming campaigns",
                        expected_impact=f"Save ${finding.get('total_wasted_spend', 0):.2f}",
                        effort="low",
                        timeline="< 1 hour",
                        steps=[
                            "Review underperforming campaigns",
                            "Pause campaigns below threshold",
                            "Reallocate budget to winners"
                        ]
                    ))
                elif finding_type == "creative_fatigue":
                    actions.append(OptimizationAction(
                        action_type="refresh_creatives",
                        priority="high",
                        description="Refresh fatigued creatives",
                        expected_impact=finding.get("estimated_performance_loss", "Unknown"),
                        effort="medium",
                        timeline="1-2 days",
                        steps=[
                            "Create new creative variations",
                            "Pause fatigued creatives",
                            "Launch refreshed creatives"
                        ]
                    ))
                elif finding_type == "audience_efficiency":
                    actions.append(OptimizationAction(
                        action_type="optimize_audiences",
                        priority="medium",
                        description="Optimize audience targeting",
                        expected_impact=finding.get("estimated_impact", "Unknown"),
                        effort="low",
                        timeline="< 1 day",
                        steps=[
                            "Identify overlapping audiences",
                            "Consolidate similar audiences",
                            "Exclude converted users"
                        ]
                    ))
            
            return actions
            
        except Exception as e:
            logger.error(f"Error generating cost reduction actions: {e}")
            return []
    
    def _calculate_potential_savings(
        self, 
        cost_reduction_actions: List[OptimizationAction]
    ) -> Dict[str, Any]:
        """Calculate potential savings"""
        try:
            # Simplified savings calculation
            high_impact_actions = [a for a in cost_reduction_actions if a.priority == "high"]
            
            estimated_monthly_savings = len(cost_reduction_actions) * 500  # $500 per action
            estimated_efficiency_gain = len(high_impact_actions) * 15  # 15% per high priority action
            
            return {
                "estimated_monthly_savings": f"${estimated_monthly_savings}",
                "estimated_efficiency_gain": f"{estimated_efficiency_gain}%",
                "quick_win_actions": len([a for a in cost_reduction_actions if a.effort == "low"]),
                "implementation_timeline": "1-2 weeks for all actions"
            }
            
        except Exception as e:
            logger.error(f"Error calculating potential savings: {e}")
            return {}


# Global expert workflow engine instance
_expert_workflow_engine: Optional[ExpertWorkflowEngine] = None


def get_expert_workflow_engine() -> ExpertWorkflowEngine:
    """Get the global ExpertWorkflowEngine instance"""
    global _expert_workflow_engine
    if _expert_workflow_engine is None:
        from .meta_client import get_client
        _expert_workflow_engine = ExpertWorkflowEngine(get_client())
    return _expert_workflow_engine
