"""
Intelligent Quick Actions for Meta Ads MCP Server

This module provides one-call solutions for complex workflows that combine
multiple Meta API operations into intelligent, automated actions.
"""

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

from .meta_client import MetaClient
from .schemas import (
    PauseUnderperformersRequest,
    ScaleWinnersRequest,
    RotateCreativesRequest,
    RebalanceBudgetsRequest,
    DuplicateWinnerRequest,
    EmergencyStopRequest,
    SmartOptimizationRequest,
    PauseUnderperformersResponse,
    ScaleWinnersResponse,
    RotateCreativesResponse,
    RebalanceBudgetsResponse,
    DuplicateWinnerResponse,
    EmergencyStopResponse,
    SmartOptimizationResponse,
    ActionResult,
    OptimizationPlan,
)
from .logging import get_logger

logger = get_logger(__name__)


@dataclass
class QuickActionContext:
    """Context for quick action operations"""
    ad_account_id: str
    time_range: Dict[str, str]
    performance_metrics: List[str]
    thresholds: Dict[str, float]
    action_parameters: Dict[str, Any]


class QuickActionEngine:
    """Handles intelligent quick actions for Meta Ads"""
    
    def __init__(self, client: MetaClient):
        self.client = client
    
    async def pause_underperformers(
        self, 
        request: PauseUnderperformersRequest
    ) -> PauseUnderperformersResponse:
        """Find and pause underperforming campaigns/adsets/ads"""
        try:
            context = QuickActionContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                performance_metrics=request.performance_metrics,
                thresholds=request.thresholds,
                action_parameters=request.action_parameters
            )
            
            # Get performance data
            performance_data = await self._get_performance_data(context, request.object_type)
            
            # Identify underperformers
            underperformers = await self._identify_underperformers(
                performance_data, request.thresholds, request.minimum_spend
            )
            
            # Pause underperformers
            pause_results = []
            for entity in underperformers:
                result = await self._pause_entity(entity, request.object_type)
                pause_results.append(result)
            
            # Calculate impact
            total_spend_saved = sum(result.get("spend_saved", 0) for result in pause_results)
            total_entities_paused = len([r for r in pause_results if r.get("success", False)])
            
            return PauseUnderperformersResponse(
                action_results=pause_results,
                total_entities_paused=total_entities_paused,
                total_spend_saved=total_spend_saved,
                underperformers_identified=len(underperformers),
                object_type=request.object_type,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error pausing underperformers: {e}")
            raise
    
    async def scale_winners(
        self, 
        request: ScaleWinnersRequest
    ) -> ScaleWinnersResponse:
        """Automatically increase budgets for top performers"""
        try:
            context = QuickActionContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                performance_metrics=request.performance_metrics,
                thresholds=request.thresholds,
                action_parameters=request.action_parameters
            )
            
            # Get performance data
            performance_data = await self._get_performance_data(context, request.object_type)
            
            # Identify winners
            winners = await self._identify_winners(
                performance_data, request.performance_threshold, request.minimum_spend
            )
            
            # Scale winners
            scaling_results = []
            for entity in winners:
                result = await self._scale_entity(
                    entity, request.scale_percentage, request.max_budget_increase
                )
                scaling_results.append(result)
            
            # Calculate impact
            total_budget_increase = sum(result.get("budget_increase", 0) for result in scaling_results)
            total_entities_scaled = len([r for r in scaling_results if r.get("success", False)])
            
            return ScaleWinnersResponse(
                action_results=scaling_results,
                total_entities_scaled=total_entities_scaled,
                total_budget_increase=total_budget_increase,
                winners_identified=len(winners),
                object_type=request.object_type,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error scaling winners: {e}")
            raise
    
    async def rotate_creatives(
        self, 
        request: RotateCreativesRequest
    ) -> RotateCreativesResponse:
        """Find fatigued creatives and rotate them"""
        try:
            context = QuickActionContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                performance_metrics=["impressions", "clicks", "ctr", "frequency"],
                thresholds=request.fatigue_thresholds,
                action_parameters=request.action_parameters
            )
            
            # Get creative performance data
            creative_data = await self._get_creative_performance_data(context)
            
            # Identify fatigued creatives
            fatigued_creatives = await self._identify_fatigued_creatives(
                creative_data, request.fatigue_thresholds
            )
            
            # Rotate creatives
            rotation_results = []
            for creative in fatigued_creatives:
                result = await self._rotate_creative(creative, request.rotation_strategy)
                rotation_results.append(result)
            
            # Calculate impact
            total_creatives_rotated = len([r for r in rotation_results if r.get("success", False)])
            
            return RotateCreativesResponse(
                action_results=rotation_results,
                total_creatives_rotated=total_creatives_rotated,
                fatigued_creatives_identified=len(fatigued_creatives),
                rotation_strategy=request.rotation_strategy,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error rotating creatives: {e}")
            raise
    
    async def rebalance_budgets(
        self, 
        request: RebalanceBudgetsRequest
    ) -> RebalanceBudgetsResponse:
        """Redistribute budgets based on performance"""
        try:
            context = QuickActionContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                performance_metrics=request.performance_metrics,
                thresholds=request.rebalancing_thresholds,
                action_parameters=request.action_parameters
            )
            
            # Get performance data
            performance_data = await self._get_performance_data(context, request.object_type)
            
            # Calculate optimal budget allocation
            optimal_allocation = await self._calculate_optimal_budget_allocation(
                performance_data, request.rebalancing_strategy
            )
            
            # Apply budget rebalancing
            rebalancing_results = []
            for allocation in optimal_allocation:
                result = await self._rebalance_entity_budget(allocation)
                rebalancing_results.append(result)
            
            # Calculate impact
            total_budget_redistributed = sum(result.get("budget_change", 0) for result in rebalancing_results)
            total_entities_rebalanced = len([r for r in rebalancing_results if r.get("success", False)])
            
            return RebalanceBudgetsResponse(
                action_results=rebalancing_results,
                total_entities_rebalanced=total_entities_rebalanced,
                total_budget_redistributed=total_budget_redistributed,
                rebalancing_strategy=request.rebalancing_strategy,
                object_type=request.object_type,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error rebalancing budgets: {e}")
            raise
    
    async def duplicate_winner(
        self, 
        request: DuplicateWinnerRequest
    ) -> DuplicateWinnerResponse:
        """Clone a winning campaign with variations"""
        try:
            context = QuickActionContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                performance_metrics=request.performance_metrics,
                thresholds=request.winner_thresholds,
                action_parameters=request.action_parameters
            )
            
            # Get performance data to identify winner
            performance_data = await self._get_performance_data(context, "campaign")
            
            # Identify winning campaign
            winner = await self._identify_winning_campaign(
                performance_data, request.winner_thresholds
            )
            
            if not winner:
                return DuplicateWinnerResponse(
                    action_results=[],
                    winner_identified=False,
                    campaigns_created=0,
                    duplication_strategy=request.duplication_strategy,
                    time_range=request.time_range,
                    generated_at=datetime.utcnow()
                )
            
            # Duplicate campaign with variations
            duplication_results = []
            for i in range(request.number_of_variations):
                result = await self._duplicate_campaign_with_variations(
                    winner, request.duplication_strategy, i + 1
                )
                duplication_results.append(result)
            
            # Calculate impact
            total_campaigns_created = len([r for r in duplication_results if r.get("success", False)])
            
            return DuplicateWinnerResponse(
                action_results=duplication_results,
                winner_identified=True,
                campaigns_created=total_campaigns_created,
                duplication_strategy=request.duplication_strategy,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error duplicating winner: {e}")
            raise
    
    async def emergency_stop(
        self, 
        request: EmergencyStopRequest
    ) -> EmergencyStopResponse:
        """Pause everything in an account"""
        try:
            context = QuickActionContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                performance_metrics=[],
                thresholds={},
                action_parameters=request.action_parameters
            )
            
            # Get all active entities
            active_entities = await self._get_all_active_entities(context, request.entity_types)
            
            # Pause all entities
            pause_results = []
            for entity_type, entities in active_entities.items():
                for entity in entities:
                    result = await self._pause_entity(entity, entity_type)
                    pause_results.append(result)
            
            # Calculate impact
            total_entities_paused = len([r for r in pause_results if r.get("success", False)])
            total_spend_saved = sum(result.get("spend_saved", 0) for result in pause_results)
            
            return EmergencyStopResponse(
                action_results=pause_results,
                total_entities_paused=total_entities_paused,
                total_spend_saved=total_spend_saved,
                entity_types=request.entity_types,
                emergency_reason=request.emergency_reason,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error in emergency stop: {e}")
            raise
    
    async def smart_optimization(
        self, 
        request: SmartOptimizationRequest
    ) -> SmartOptimizationResponse:
        """Full account optimization in one call"""
        try:
            context = QuickActionContext(
                ad_account_id=request.ad_account_id,
                time_range=request.time_range,
                performance_metrics=request.performance_metrics,
                thresholds=request.optimization_thresholds,
                action_parameters=request.action_parameters
            )
            
            # Get comprehensive account data
            account_data = await self._get_comprehensive_account_data(context)
            
            # Create optimization plan
            optimization_plan = await self._create_optimization_plan(
                account_data, request.optimization_strategy
            )
            
            # Execute optimization plan
            optimization_results = []
            for action in optimization_plan.actions:
                result = await self._execute_optimization_action(action)
                optimization_results.append(result)
            
            # Calculate impact
            total_actions_executed = len([r for r in optimization_results if r.get("success", False)])
            total_impact_score = sum(result.get("impact_score", 0) for result in optimization_results)
            
            return SmartOptimizationResponse(
                action_results=optimization_results,
                total_actions_executed=total_actions_executed,
                total_impact_score=total_impact_score,
                optimization_plan=optimization_plan,
                optimization_strategy=request.optimization_strategy,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error in smart optimization: {e}")
            raise
    
    async def _get_performance_data(
        self, 
        context: QuickActionContext, 
        object_type: str
    ) -> List[Dict[str, Any]]:
        """Get performance data for entities"""
        try:
            # Get insights with specified metrics
            if object_type == "campaign":
                path = f"{context.ad_account_id}/insights"
                params = {
                    "level": "campaign",
                    "fields": ",".join(context.performance_metrics),
                    "time_range": context.time_range,
                    "limit": 1000
                }
            elif object_type == "adset":
                path = f"{context.ad_account_id}/insights"
                params = {
                    "level": "adset",
                    "fields": ",".join(context.performance_metrics),
                    "time_range": context.time_range,
                    "limit": 1000
                }
            elif object_type == "ad":
                path = f"{context.ad_account_id}/insights"
                params = {
                    "level": "ad",
                    "fields": ",".join(context.performance_metrics),
                    "time_range": context.time_range,
                    "limit": 1000
                }
            else:
                raise ValueError(f"Unsupported object type: {object_type}")
            
            insights_response = await self.client.graph_request(
                method="GET",
                path=path,
                params=params
            )
            
            return insights_response.get("data", [])
            
        except Exception as e:
            logger.error(f"Error getting performance data: {e}")
            return []
    
    async def _get_creative_performance_data(
        self, 
        context: QuickActionContext
    ) -> List[Dict[str, Any]]:
        """Get creative performance data"""
        try:
            # Get ad insights with creative breakdown
            path = f"{context.ad_account_id}/insights"
            params = {
                "level": "ad",
                "fields": ",".join(context.performance_metrics),
                "time_range": context.time_range,
                "breakdowns": ["creative_id"],
                "limit": 1000
            }
            
            insights_response = await self.client.graph_request(
                method="GET",
                path=path,
                params=params
            )
            
            return insights_response.get("data", [])
            
        except Exception as e:
            logger.error(f"Error getting creative performance data: {e}")
            return []
    
    async def _identify_underperformers(
        self, 
        performance_data: List[Dict[str, Any]], 
        thresholds: Dict[str, float],
        minimum_spend: float
    ) -> List[Dict[str, Any]]:
        """Identify underperforming entities"""
        try:
            underperformers = []
            
            for data in performance_data:
                spend = float(data.get("spend", 0))
                
                # Skip if below minimum spend
                if spend < minimum_spend:
                    continue
                
                # Check performance against thresholds
                is_underperforming = False
                for metric, threshold in thresholds.items():
                    metric_value = float(data.get(metric, 0))
                    if metric_value < threshold:
                        is_underperforming = True
                        break
                
                if is_underperforming:
                    underperformers.append(data)
            
            return underperformers
            
        except Exception as e:
            logger.error(f"Error identifying underperformers: {e}")
            return []
    
    async def _identify_winners(
        self, 
        performance_data: List[Dict[str, Any]], 
        performance_threshold: float,
        minimum_spend: float
    ) -> List[Dict[str, Any]]:
        """Identify winning entities"""
        try:
            winners = []
            
            for data in performance_data:
                spend = float(data.get("spend", 0))
                
                # Skip if below minimum spend
                if spend < minimum_spend:
                    continue
                
                # Check if entity is a winner (simplified logic)
                # In reality, this would use more sophisticated criteria
                conversions = int(data.get("conversions", 0))
                if conversions > 0 and spend > 0:
                    roas = conversions / spend  # Simplified ROAS calculation
                    if roas > performance_threshold:
                        winners.append(data)
            
            return winners
            
        except Exception as e:
            logger.error(f"Error identifying winners: {e}")
            return []
    
    async def _identify_fatigued_creatives(
        self, 
        creative_data: List[Dict[str, Any]], 
        fatigue_thresholds: Dict[str, float]
    ) -> List[Dict[str, Any]]:
        """Identify fatigued creatives"""
        try:
            fatigued_creatives = []
            
            for data in creative_data:
                # Check fatigue indicators
                frequency = float(data.get("frequency", 0))
                ctr = float(data.get("ctr", 0))
                
                # Simple fatigue detection logic
                if frequency > fatigue_thresholds.get("frequency", 3.0) or ctr < fatigue_thresholds.get("ctr", 1.0):
                    fatigued_creatives.append(data)
            
            return fatigued_creatives
            
        except Exception as e:
            logger.error(f"Error identifying fatigued creatives: {e}")
            return []
    
    async def _identify_winning_campaign(
        self, 
        performance_data: List[Dict[str, Any]], 
        winner_thresholds: Dict[str, float]
    ) -> Optional[Dict[str, Any]]:
        """Identify the best performing campaign"""
        try:
            if not performance_data:
                return None
            
            # Find campaign with best performance
            best_campaign = None
            best_score = 0
            
            for data in performance_data:
                # Calculate performance score (simplified)
                conversions = int(data.get("conversions", 0))
                spend = float(data.get("spend", 0))
                
                if spend > 0:
                    score = conversions / spend  # Simplified scoring
                    if score > best_score:
                        best_score = score
                        best_campaign = data
            
            return best_campaign
            
        except Exception as e:
            logger.error(f"Error identifying winning campaign: {e}")
            return None
    
    async def _pause_entity(
        self, 
        entity: Dict[str, Any], 
        object_type: str
    ) -> ActionResult:
        """Pause an entity"""
        try:
            entity_id = entity.get("campaign_id") or entity.get("adset_id") or entity.get("ad_id")
            
            # Update entity status to PAUSED
            await self.client.graph_request(
                method="POST",
                path=entity_id,
                params={"status": "PAUSED"}
            )
            
            spend = float(entity.get("spend", 0))
            
            return ActionResult(
                entity_id=entity_id,
                entity_name=entity.get("campaign_name") or entity.get("adset_name") or entity.get("ad_name"),
                action="pause",
                success=True,
                spend_saved=spend,
                impact_score=self._calculate_impact_score("pause", spend)
            )
            
        except Exception as e:
            logger.error(f"Error pausing entity: {e}")
            return ActionResult(
                entity_id=entity.get("campaign_id") or entity.get("adset_id") or entity.get("ad_id"),
                entity_name=entity.get("campaign_name") or entity.get("adset_name") or entity.get("ad_name"),
                action="pause",
                success=False,
                error=str(e),
                impact_score=0
            )
    
    async def _scale_entity(
        self, 
        entity: Dict[str, Any], 
        scale_percentage: float,
        max_budget_increase: float
    ) -> ActionResult:
        """Scale an entity's budget"""
        try:
            entity_id = entity.get("campaign_id") or entity.get("adset_id")
            
            # Get current budget
            current_budget = float(entity.get("daily_budget", 0))
            
            # Calculate new budget
            budget_increase = current_budget * (scale_percentage / 100)
            new_budget = min(current_budget + budget_increase, current_budget + max_budget_increase)
            
            # Update budget
            await self.client.graph_request(
                method="POST",
                path=entity_id,
                params={"daily_budget": new_budget}
            )
            
            return ActionResult(
                entity_id=entity_id,
                entity_name=entity.get("campaign_name") or entity.get("adset_name"),
                action="scale",
                success=True,
                budget_increase=new_budget - current_budget,
                impact_score=self._calculate_impact_score("scale", new_budget - current_budget)
            )
            
        except Exception as e:
            logger.error(f"Error scaling entity: {e}")
            return ActionResult(
                entity_id=entity.get("campaign_id") or entity.get("adset_id"),
                entity_name=entity.get("campaign_name") or entity.get("adset_name"),
                action="scale",
                success=False,
                error=str(e),
                impact_score=0
            )
    
    async def _rotate_creative(
        self, 
        creative: Dict[str, Any], 
        rotation_strategy: str
    ) -> ActionResult:
        """Rotate a creative"""
        try:
            creative_id = creative.get("creative_id")
            ad_id = creative.get("ad_id")
            
            # Pause current ad
            await self.client.graph_request(
                method="POST",
                path=ad_id,
                params={"status": "PAUSED"}
            )
            
            # Create new ad with different creative (simplified)
            # In reality, this would involve more complex creative rotation logic
            
            return ActionResult(
                entity_id=creative_id,
                entity_name=f"Creative {creative_id}",
                action="rotate",
                success=True,
                impact_score=self._calculate_impact_score("rotate", 1)
            )
            
        except Exception as e:
            logger.error(f"Error rotating creative: {e}")
            return ActionResult(
                entity_id=creative.get("creative_id"),
                entity_name=f"Creative {creative.get('creative_id')}",
                action="rotate",
                success=False,
                error=str(e),
                impact_score=0
            )
    
    async def _rebalance_entity_budget(
        self, 
        allocation: Dict[str, Any]
    ) -> ActionResult:
        """Rebalance entity budget"""
        try:
            entity_id = allocation.get("entity_id")
            new_budget = allocation.get("new_budget")
            current_budget = allocation.get("current_budget")
            
            # Update budget
            await self.client.graph_request(
                method="POST",
                path=entity_id,
                params={"daily_budget": new_budget}
            )
            
            return ActionResult(
                entity_id=entity_id,
                entity_name=allocation.get("entity_name"),
                action="rebalance",
                success=True,
                budget_change=new_budget - current_budget,
                impact_score=self._calculate_impact_score("rebalance", abs(new_budget - current_budget))
            )
            
        except Exception as e:
            logger.error(f"Error rebalancing entity budget: {e}")
            return ActionResult(
                entity_id=allocation.get("entity_id"),
                entity_name=allocation.get("entity_name"),
                action="rebalance",
                success=False,
                error=str(e),
                impact_score=0
            )
    
    async def _duplicate_campaign_with_variations(
        self, 
        winner: Dict[str, Any], 
        duplication_strategy: str,
        variation_number: int
    ) -> ActionResult:
        """Duplicate campaign with variations"""
        try:
            campaign_id = winner.get("campaign_id")
            
            # Get campaign details
            campaign_response = await self.client.graph_request(
                method="GET",
                path=campaign_id,
                params={"fields": "name,objective,status"}
            )
            
            # Create new campaign with variations
            new_campaign_name = f"{campaign_response.get('name', 'Campaign')} - Variation {variation_number}"
            
            new_campaign_response = await self.client.graph_request(
                method="POST",
                path=f"{self.client.ad_account_id}/campaigns",
                params={
                    "name": new_campaign_name,
                    "objective": campaign_response.get("objective"),
                    "status": "PAUSED"  # Start paused for review
                }
            )
            
            new_campaign_id = new_campaign_response.get("id")
            
            return ActionResult(
                entity_id=new_campaign_id,
                entity_name=new_campaign_name,
                action="duplicate",
                success=True,
                impact_score=self._calculate_impact_score("duplicate", 1)
            )
            
        except Exception as e:
            logger.error(f"Error duplicating campaign: {e}")
            return ActionResult(
                entity_id=winner.get("campaign_id"),
                entity_name=winner.get("campaign_name"),
                action="duplicate",
                success=False,
                error=str(e),
                impact_score=0
            )
    
    async def _get_all_active_entities(
        self, 
        context: QuickActionContext, 
        entity_types: List[str]
    ) -> Dict[str, List[Dict[str, Any]]]:
        """Get all active entities in account"""
        try:
            active_entities = {}
            
            for entity_type in entity_types:
                if entity_type == "campaign":
                    path = f"{context.ad_account_id}/campaigns"
                    params = {"fields": "id,name,status", "limit": 1000}
                elif entity_type == "adset":
                    path = f"{context.ad_account_id}/adsets"
                    params = {"fields": "id,name,status", "limit": 1000}
                elif entity_type == "ad":
                    path = f"{context.ad_account_id}/ads"
                    params = {"fields": "id,name,status", "limit": 1000}
                else:
                    continue
                
                response = await self.client.graph_request(
                    method="GET",
                    path=path,
                    params=params
                )
                
                # Filter for active entities
                active_entities[entity_type] = [
                    entity for entity in response.get("data", [])
                    if entity.get("status") == "ACTIVE"
                ]
            
            return active_entities
            
        except Exception as e:
            logger.error(f"Error getting active entities: {e}")
            return {}
    
    async def _create_optimization_plan(
        self, 
        account_data: Dict[str, Any], 
        optimization_strategy: str
    ) -> OptimizationPlan:
        """Create comprehensive optimization plan"""
        try:
            # This is a simplified optimization plan
            # In reality, this would involve sophisticated analysis and planning
            
            actions = [
                {
                    "action_type": "pause_underperformers",
                    "description": "Pause campaigns with ROAS < 2.0",
                    "priority": "high"
                },
                {
                    "action_type": "scale_winners",
                    "description": "Increase budget for campaigns with ROAS > 4.0",
                    "priority": "high"
                },
                {
                    "action_type": "rebalance_budgets",
                    "description": "Redistribute budgets based on performance",
                    "priority": "medium"
                }
            ]
            
            return OptimizationPlan(
                strategy=optimization_strategy,
                actions=actions,
                estimated_impact="high",
                execution_time="5-10 minutes"
            )
            
        except Exception as e:
            logger.error(f"Error creating optimization plan: {e}")
            return OptimizationPlan(
                strategy=optimization_strategy,
                actions=[],
                estimated_impact="unknown",
                execution_time="unknown"
            )
    
    async def _execute_optimization_action(
        self, 
        action: Dict[str, Any]
    ) -> ActionResult:
        """Execute an optimization action"""
        try:
            action_type = action.get("action_type")
            
            # Simplified action execution
            # In reality, this would call the appropriate optimization method
            
            return ActionResult(
                entity_id="optimization_action",
                entity_name=action.get("description", "Optimization Action"),
                action=action_type,
                success=True,
                impact_score=self._calculate_impact_score(action_type, 1)
            )
            
        except Exception as e:
            logger.error(f"Error executing optimization action: {e}")
            return ActionResult(
                entity_id="optimization_action",
                entity_name=action.get("description", "Optimization Action"),
                action=action.get("action_type", "unknown"),
                success=False,
                error=str(e),
                impact_score=0
            )
    
    async def _get_comprehensive_account_data(
        self, 
        context: QuickActionContext
    ) -> Dict[str, Any]:
        """Get comprehensive account data for optimization"""
        try:
            # Get campaigns, adsets, and ads data
            campaigns = await self._get_performance_data(context, "campaign")
            adsets = await self._get_performance_data(context, "adset")
            ads = await self._get_performance_data(context, "ad")
            
            return {
                "campaigns": campaigns,
                "adsets": adsets,
                "ads": ads,
                "account_id": context.ad_account_id,
                "time_range": context.time_range
            }
            
        except Exception as e:
            logger.error(f"Error getting comprehensive account data: {e}")
            return {}
    
    async def _calculate_optimal_budget_allocation(
        self, 
        performance_data: List[Dict[str, Any]], 
        rebalancing_strategy: str
    ) -> List[Dict[str, Any]]:
        """Calculate optimal budget allocation"""
        try:
            # Simplified budget allocation logic
            # In reality, this would use sophisticated optimization algorithms
            
            total_budget = sum(float(data.get("daily_budget", 0)) for data in performance_data)
            allocations = []
            
            for data in performance_data:
                entity_id = data.get("campaign_id") or data.get("adset_id")
                current_budget = float(data.get("daily_budget", 0))
                performance_score = float(data.get("conversions", 0)) / max(float(data.get("spend", 1)), 1)
                
                # Allocate budget based on performance
                new_budget = total_budget * (performance_score / sum(
                    float(d.get("conversions", 0)) / max(float(d.get("spend", 1)), 1) 
                    for d in performance_data
                ))
                
                allocations.append({
                    "entity_id": entity_id,
                    "entity_name": data.get("campaign_name") or data.get("adset_name"),
                    "current_budget": current_budget,
                    "new_budget": new_budget
                })
            
            return allocations
            
        except Exception as e:
            logger.error(f"Error calculating optimal budget allocation: {e}")
            return []
    
    def _calculate_impact_score(
        self, 
        action_type: str, 
        value: float
    ) -> float:
        """Calculate impact score for an action"""
        try:
            # Simplified impact scoring
            base_scores = {
                "pause": 0.8,
                "scale": 0.6,
                "rotate": 0.4,
                "rebalance": 0.7,
                "duplicate": 0.5
            }
            
            base_score = base_scores.get(action_type, 0.5)
            return base_score * min(value / 100, 1.0)  # Normalize value impact
            
        except Exception:
            return 0.5


# Global quick action engine instance
_quick_action_engine: Optional[QuickActionEngine] = None


def get_quick_action_engine() -> QuickActionEngine:
    """Get the global QuickActionEngine instance"""
    global _quick_action_engine
    if _quick_action_engine is None:
        from .meta_client import get_client
        _quick_action_engine = QuickActionEngine(get_client())
    return _quick_action_engine
