"""
Cost & Efficiency Analysis Module for Meta Ads MCP Server

This module provides advanced cost analysis and efficiency optimization tools
that enable LLMs to identify wasted spend and optimize budget allocation.
"""

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

from .meta_client import MetaClient
from .schemas import (
    MarginalCPARequest,
    MarginalCPAResponse,
    WastedSpendRequest,
    WastedSpendResponse,
    CrossCampaignEfficiencyRequest,
    CrossCampaignEfficiencyResponse,
    CACTrendRequest,
    CACTrendResponse,
    BudgetPacingDiagnosticRequest,
    BudgetPacingDiagnosticResponse,
    ValueBiddingAnalysisRequest,
    ValueBiddingAnalysisResponse,
    QualityQuantityTradeoffRequest,
    QualityQuantityTradeoffResponse,
    AuctionCompetitivenessRequest,
    AuctionCompetitivenessResponse,
    AccountSpendEfficiencyRequest,
    AccountSpendEfficiencyResponse,
    ProfitMarginRequest,
    ProfitMarginResponse,
)
from .logging import get_logger

logger = get_logger(__name__)


@dataclass
class CostAnalysisContext:
    """Context for cost analysis operations"""
    ad_account_id: str
    time_range: Dict[str, str]
    cost_structure: Optional[Dict[str, float]] = None


class CostEfficiencyAnalysisEngine:
    """Handles cost and efficiency analysis operations for Meta Ads"""
    
    def __init__(self, client: MetaClient):
        self.client = client
    
    async def calculate_marginal_cpa(
        self, 
        request: MarginalCPARequest
    ) -> MarginalCPAResponse:
        """
        Calculate marginal cost per acquisition (incremental CPA).
        
        Determines the cost of the next conversion at different spend levels
        to identify diminishing returns and optimal spend points.
        """
        try:
            # Get historical spend and conversion data
            insights = await self.client.get(
                f"{request.entity_id}/insights",
                params={
                    "time_range": request.time_range,
                    "fields": "spend,conversions,cpa",
                    "time_increment": "1",
                    "level": request.entity_type
                }
            )
            
            daily_data = insights.get("data", [])
            
            # Calculate marginal CPA for different spend levels
            marginal_analysis = []
            sorted_data = sorted(daily_data, key=lambda x: float(x.get("spend", 0)))
            
            for i in range(1, len(sorted_data)):
                prev = sorted_data[i-1]
                curr = sorted_data[i]
                
                spend_increase = float(curr.get("spend", 0)) - float(prev.get("spend", 0))
                conversion_increase = int(curr.get("conversions", 0)) - int(prev.get("conversions", 0))
                
                if conversion_increase > 0:
                    marginal_cpa = spend_increase / conversion_increase
                    
                    marginal_analysis.append({
                        "spend_level": float(curr.get("spend", 0)),
                        "conversions": int(curr.get("conversions", 0)),
                        "average_cpa": float(curr.get("cpa", 0)),
                        "marginal_cpa": round(marginal_cpa, 2),
                        "efficiency_score": self._calculate_marginal_efficiency(
                            marginal_cpa, float(curr.get("cpa", 0))
                        )
                    })
            
            # Identify diminishing returns threshold
            diminishing_threshold = self._find_diminishing_returns_threshold(marginal_analysis)
            
            # Calculate optimal spend level
            optimal_spend = self._calculate_optimal_spend_level(
                marginal_analysis, request.target_cpa
            )
            
            # Generate recommendations
            recommendations = self._generate_marginal_cpa_recommendations(
                marginal_analysis, diminishing_threshold, optimal_spend, request.target_cpa
            )
            
            return MarginalCPAResponse(
                marginal_analysis=marginal_analysis,
                diminishing_returns_threshold=diminishing_threshold,
                optimal_spend_level=optimal_spend,
                recommendations=recommendations,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error calculating marginal CPA: {e}")
            raise
    
    async def identify_wasted_spend(
        self, 
        request: WastedSpendRequest
    ) -> WastedSpendResponse:
        """
        Identify wasted spend across placements, demographics, and time periods.
        
        Analyzes performance to find non-converting segments and provides
        reallocation recommendations.
        """
        try:
            # Get detailed breakdown of spend
            insights = await self.client.get(
                f"{request.ad_account_id}/insights",
                params={
                    "time_range": request.time_range,
                    "fields": "spend,conversions,cpa,roas",
                    "breakdowns": "age,gender,publisher_platform,hourly_stats_aggregated_by_advertiser_time_zone",
                    "level": "account"
                }
            )
            
            segments = insights.get("data", [])
            
            # Identify wasted spend segments
            wasted_segments = []
            total_wasted = 0.0
            
            for segment in segments:
                spend = float(segment.get("spend", 0))
                conversions = int(segment.get("conversions", 0))
                roas = float(segment.get("roas", 0))
                
                # Criteria for wasted spend
                is_wasted = False
                waste_reason = []
                
                if conversions == 0 and spend > request.min_spend_threshold:
                    is_wasted = True
                    waste_reason.append("zero_conversions")
                
                if roas < request.min_roas_threshold and spend > request.min_spend_threshold:
                    is_wasted = True
                    waste_reason.append("poor_roas")
                
                if segment.get("cpa") and float(segment.get("cpa", 0)) > request.max_cpa_threshold:
                    is_wasted = True
                    waste_reason.append("high_cpa")
                
                if is_wasted:
                    wasted_segments.append({
                        "segment_id": self._create_segment_id(segment),
                        "age": segment.get("age"),
                        "gender": segment.get("gender"),
                        "platform": segment.get("publisher_platform"),
                        "hour": segment.get("hourly_stats_aggregated_by_advertiser_time_zone"),
                        "spend": spend,
                        "conversions": conversions,
                        "waste_reasons": waste_reason,
                        "severity": self._calculate_waste_severity(spend, conversions, roas)
                    })
                    total_wasted += spend
            
            # Sort by spend (highest waste first)
            wasted_segments.sort(key=lambda x: x["spend"], reverse=True)
            
            # Generate reallocation recommendations
            reallocation_plan = self._generate_reallocation_plan(
                wasted_segments, total_wasted
            )
            
            # Generate recommendations
            recommendations = self._generate_wasted_spend_recommendations(
                wasted_segments, total_wasted, reallocation_plan
            )
            
            return WastedSpendResponse(
                total_wasted_spend=round(total_wasted, 2),
                wasted_segments=wasted_segments[:20],  # Top 20
                reallocation_plan=reallocation_plan,
                recommendations=recommendations,
                potential_savings_percentage=round((total_wasted / request.total_budget * 100), 2) if request.total_budget > 0 else 0,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error identifying wasted spend: {e}")
            raise
    
    async def compare_cross_campaign_efficiency(
        self, 
        request: CrossCampaignEfficiencyRequest
    ) -> CrossCampaignEfficiencyResponse:
        """
        Compare efficiency across campaigns for portfolio optimization.
        
        Provides efficiency scores and budget reallocation modeling to
        optimize overall portfolio performance.
        """
        try:
            # Get all campaigns with performance data
            campaigns_data = []
            
            for campaign_id in request.campaign_ids:
                insights = await self.client.get(
                    f"{campaign_id}/insights",
                    params={
                        "time_range": request.time_range,
                        "fields": "campaign_name,spend,conversions,cpa,roas,ctr,frequency"
                    }
                )
                
                data = insights.get("data", [{}])[0]
                data["campaign_id"] = campaign_id
                campaigns_data.append(data)
            
            # Calculate efficiency scores
            campaign_efficiency = []
            
            for campaign in campaigns_data:
                efficiency_score = self._calculate_campaign_efficiency_score(campaign)
                
                campaign_efficiency.append({
                    "campaign_id": campaign["campaign_id"],
                    "campaign_name": campaign.get("campaign_name", "Unknown"),
                    "spend": float(campaign.get("spend", 0)),
                    "conversions": int(campaign.get("conversions", 0)),
                    "cpa": float(campaign.get("cpa", 0)),
                    "roas": float(campaign.get("roas", 0)),
                    "efficiency_score": efficiency_score,
                    "efficiency_tier": self._determine_efficiency_tier(efficiency_score),
                    "roi_contribution": self._calculate_roi_contribution(campaign, campaigns_data)
                })
            
            # Sort by efficiency score
            campaign_efficiency.sort(key=lambda x: x["efficiency_score"], reverse=True)
            
            # Generate reallocation model
            reallocation_model = self._model_budget_reallocation(
                campaign_efficiency, request.total_budget
            )
            
            # Calculate portfolio metrics
            portfolio_metrics = self._calculate_portfolio_metrics(campaign_efficiency)
            
            # Generate recommendations
            recommendations = self._generate_cross_campaign_recommendations(
                campaign_efficiency, reallocation_model, portfolio_metrics
            )
            
            return CrossCampaignEfficiencyResponse(
                campaign_efficiency=campaign_efficiency,
                reallocation_model=reallocation_model,
                portfolio_metrics=portfolio_metrics,
                recommendations=recommendations,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error comparing cross-campaign efficiency: {e}")
            raise
    
    async def analyze_cac_trend(
        self, 
        request: CACTrendRequest
    ) -> CACTrendResponse:
        """
        Analyze Customer Acquisition Cost trends and calculate payback periods.
        
        Tracks CAC evolution over time and determines profitability thresholds.
        """
        try:
            # Get CAC data over time
            insights = await self.client.get(
                f"{request.ad_account_id}/insights",
                params={
                    "time_range": request.time_range,
                    "fields": "spend,conversions,cpa",
                    "time_increment": request.time_increment or "monthly",
                    "level": "account"
                }
            )
            
            time_series_data = insights.get("data", [])
            
            # Calculate CAC trend
            cac_trend = []
            for period in time_series_data:
                cac = float(period.get("cpa", 0))
                
                cac_trend.append({
                    "period": period.get("date_start"),
                    "cac": cac,
                    "conversions": int(period.get("conversions", 0)),
                    "spend": float(period.get("spend", 0))
                })
            
            # Calculate trend metrics
            cac_values = [p["cac"] for p in cac_trend if p["cac"] > 0]
            trend_analysis = {
                "average_cac": round(statistics.mean(cac_values), 2) if cac_values else 0,
                "median_cac": round(statistics.median(cac_values), 2) if cac_values else 0,
                "cac_volatility": round(statistics.stdev(cac_values), 2) if len(cac_values) > 1 else 0,
                "trend_direction": self._calculate_trend_direction(cac_values),
                "trend_strength": self._calculate_trend_strength(cac_values)
            }
            
            # Calculate payback period
            payback_analysis = self._calculate_payback_period(
                trend_analysis["average_cac"],
                request.average_customer_ltv,
                request.average_margin_percentage
            )
            
            # Determine profitability threshold
            profitability_threshold = self._calculate_profitability_threshold(
                request.average_customer_ltv,
                request.average_margin_percentage
            )
            
            # Generate recommendations
            recommendations = self._generate_cac_recommendations(
                trend_analysis, payback_analysis, profitability_threshold
            )
            
            return CACTrendResponse(
                cac_trend=cac_trend,
                trend_analysis=trend_analysis,
                payback_analysis=payback_analysis,
                profitability_threshold=profitability_threshold,
                recommendations=recommendations,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error analyzing CAC trend: {e}")
            raise
    
    async def diagnose_budget_pacing(
        self, 
        request: BudgetPacingDiagnosticRequest
    ) -> BudgetPacingDiagnosticResponse:
        """
        Diagnose budget pacing issues with underspend/overspend detection.
        
        Analyzes spending patterns and provides daily pacing recommendations.
        """
        try:
            # Get campaign budget and delivery info
            campaign_info = await self.client.get(
                request.campaign_id,
                params={
                    "fields": "name,daily_budget,lifetime_budget,budget_remaining,start_time,stop_time"
                }
            )
            
            # Get spend data
            insights = await self.client.get(
                f"{request.campaign_id}/insights",
                params={
                    "time_range": request.time_range,
                    "fields": "spend,impressions",
                    "time_increment": "1"
                }
            )
            
            daily_spend = insights.get("data", [])
            
            # Calculate pacing metrics
            total_spend = sum(float(d.get("spend", 0)) for d in daily_spend)
            days_elapsed = len(daily_spend)
            
            daily_budget = float(campaign_info.get("daily_budget", 0))
            expected_spend = daily_budget * days_elapsed if daily_budget > 0 else 0
            
            pacing_metrics = {
                "total_spend": round(total_spend, 2),
                "expected_spend": round(expected_spend, 2),
                "spend_variance": round(total_spend - expected_spend, 2),
                "pacing_percentage": round((total_spend / expected_spend * 100), 2) if expected_spend > 0 else 0,
                "average_daily_spend": round(total_spend / days_elapsed, 2) if days_elapsed > 0 else 0,
                "days_analyzed": days_elapsed
            }
            
            # Detect issues
            issues_detected = []
            
            if pacing_metrics["pacing_percentage"] < 80:
                issues_detected.append({
                    "issue": "underspend",
                    "severity": "high" if pacing_metrics["pacing_percentage"] < 60 else "medium",
                    "description": f"Spending only {pacing_metrics['pacing_percentage']}% of budget"
                })
            elif pacing_metrics["pacing_percentage"] > 120:
                issues_detected.append({
                    "issue": "overspend",
                    "severity": "high",
                    "description": f"Spending {pacing_metrics['pacing_percentage']}% of budget"
                })
            
            # Calculate volatility
            daily_spends = [float(d.get("spend", 0)) for d in daily_spend]
            if len(daily_spends) > 1:
                spend_volatility = statistics.stdev(daily_spends)
                if spend_volatility > pacing_metrics["average_daily_spend"] * 0.5:
                    issues_detected.append({
                        "issue": "high_volatility",
                        "severity": "medium",
                        "description": "Spending is highly inconsistent day-to-day"
                    })
            
            # Predict budget exhaustion
            budget_exhaustion_prediction = self._predict_budget_exhaustion(
                campaign_info, pacing_metrics, daily_spend
            )
            
            # Generate optimal daily budget recommendation
            optimal_daily_budget = self._calculate_optimal_daily_budget(
                campaign_info, pacing_metrics, budget_exhaustion_prediction
            )
            
            # Generate recommendations
            recommendations = self._generate_pacing_recommendations(
                issues_detected, pacing_metrics, optimal_daily_budget
            )
            
            return BudgetPacingDiagnosticResponse(
                pacing_metrics=pacing_metrics,
                issues_detected=issues_detected,
                budget_exhaustion_prediction=budget_exhaustion_prediction,
                optimal_daily_budget=optimal_daily_budget,
                recommendations=recommendations,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error diagnosing budget pacing: {e}")
            raise
    
    async def analyze_value_bidding(
        self, 
        request: ValueBiddingAnalysisRequest
    ) -> ValueBiddingAnalysisResponse:
        """
        Analyze value-based bidding effectiveness and ROAS optimization.
        
        Evaluates value optimization performance and customer LTV alignment.
        """
        try:
            # Get value optimization data
            insights = await self.client.get(
                f"{request.entity_id}/insights",
                params={
                    "time_range": request.time_range,
                    "fields": "spend,conversions,conversion_values,roas,purchase_roas",
                    "level": request.entity_type,
                    "action_breakdowns": "action_type"
                }
            )
            
            data = insights.get("data", [{}])[0]
            
            # Calculate value metrics
            value_metrics = {
                "total_spend": float(data.get("spend", 0)),
                "total_conversions": int(data.get("conversions", 0)),
                "total_conversion_value": float(data.get("conversion_values", 0)),
                "overall_roas": float(data.get("roas", 0)),
                "average_order_value": float(data.get("conversion_values", 0)) / int(data.get("conversions", 1)) if int(data.get("conversions", 0)) > 0 else 0
            }
            
            # Analyze bid strategy effectiveness
            bid_strategy_analysis = {
                "current_strategy": request.current_bid_strategy,
                "roas_vs_target": round(value_metrics["overall_roas"] - request.target_roas, 2),
                "value_optimization_effectiveness": self._calculate_value_optimization_effectiveness(value_metrics, request.target_roas),
                "ltv_alignment_score": self._calculate_ltv_alignment(value_metrics["average_order_value"], request.customer_ltv)
            }
            
            # Compare bid strategies
            strategy_comparison = self._compare_bid_strategies(
                value_metrics, request.current_bid_strategy
            )
            
            # Generate recommendations
            recommendations = self._generate_value_bidding_recommendations(
                value_metrics, bid_strategy_analysis, strategy_comparison, request.target_roas
            )
            
            return ValueBiddingAnalysisResponse(
                value_metrics=value_metrics,
                bid_strategy_analysis=bid_strategy_analysis,
                strategy_comparison=strategy_comparison,
                recommendations=recommendations,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error analyzing value bidding: {e}")
            raise
    
    async def analyze_quality_quantity_tradeoff(
        self, 
        request: QualityQuantityTradeoffRequest
    ) -> QualityQuantityTradeoffResponse:
        """
        Analyze volume vs efficiency trade-offs.
        
        Identifies optimal balance between scale and efficiency for growth.
        """
        try:
            # Get performance at different spend levels
            insights = await self.client.get(
                f"{request.entity_id}/insights",
                params={
                    "time_range": request.time_range,
                    "fields": "spend,conversions,cpa,roas",
                    "time_increment": "1",
                    "level": request.entity_type
                }
            )
            
            daily_data = insights.get("data", [])
            
            # Create volume vs CPA curve
            volume_efficiency_curve = []
            
            sorted_data = sorted(daily_data, key=lambda x: int(x.get("conversions", 0)))
            
            for data_point in sorted_data:
                volume_efficiency_curve.append({
                    "conversions": int(data_point.get("conversions", 0)),
                    "spend": float(data_point.get("spend", 0)),
                    "cpa": float(data_point.get("cpa", 0)),
                    "roas": float(data_point.get("roas", 0)),
                    "efficiency_score": self._calculate_efficiency_at_volume(data_point)
                })
            
            # Identify optimal balance point
            optimal_balance = self._find_optimal_balance_point(
                volume_efficiency_curve, request.priority
            )
            
            # Calculate scale vs efficiency analysis
            scale_analysis = {
                "current_volume": sum(int(d.get("conversions", 0)) for d in daily_data),
                "current_efficiency": statistics.mean([float(d.get("roas", 0)) for d in daily_data if d.get("roas")]),
                "growth_ceiling": self._estimate_growth_ceiling(volume_efficiency_curve),
                "efficiency_at_2x_volume": self._estimate_efficiency_at_scale(volume_efficiency_curve, 2.0),
                "efficiency_at_3x_volume": self._estimate_efficiency_at_scale(volume_efficiency_curve, 3.0)
            }
            
            # Generate recommendations
            recommendations = self._generate_tradeoff_recommendations(
                volume_efficiency_curve, optimal_balance, scale_analysis, request.priority
            )
            
            return QualityQuantityTradeoffResponse(
                volume_efficiency_curve=volume_efficiency_curve,
                optimal_balance=optimal_balance,
                scale_analysis=scale_analysis,
                recommendations=recommendations,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error analyzing quality quantity tradeoff: {e}")
            raise
    
    async def analyze_auction_competitiveness(
        self, 
        request: AuctionCompetitivenessRequest
    ) -> AuctionCompetitivenessResponse:
        """
        Analyze auction competitiveness and market dynamics.
        
        Estimates auction density, competitive pressure, and market positioning.
        """
        try:
            # Get auction competitiveness data
            insights = await self.client.get(
                f"{request.entity_id}/insights",
                params={
                    "time_range": request.time_range,
                    "fields": "spend,impressions,reach,frequency,cpm,auction_bid,auction_competitiveness,auction_overlap",
                    "level": request.entity_type
                }
            )
            
            data = insights.get("data", [{}])[0]
            
            # Calculate competitiveness metrics
            competitiveness_metrics = {
                "auction_competitiveness_score": float(data.get("auction_competitiveness", 0)),
                "estimated_auction_density": self._estimate_auction_density(data),
                "competitive_bid_pressure": self._calculate_competitive_pressure(data),
                "market_saturation_level": self._estimate_market_saturation(data),
                "win_rate_estimate": float(data.get("impressions", 0)) / (float(data.get("impressions", 1)) * 2) if data.get("impressions") else 0.5
            }
            
            # Estimate market share
            market_share_estimate = self._estimate_market_share(data, competitiveness_metrics)
            
            # Analyze competitive positioning
            positioning_analysis = {
                "current_position": self._determine_competitive_position(competitiveness_metrics),
                "relative_bid_strength": self._calculate_relative_bid_strength(data),
                "share_of_voice": market_share_estimate["share_of_voice"],
                "competitive_threats": self._identify_competitive_threats(competitiveness_metrics)
            }
            
            # Generate recommendations
            recommendations = self._generate_competitiveness_recommendations(
                competitiveness_metrics, positioning_analysis, market_share_estimate
            )
            
            return AuctionCompetitivenessResponse(
                competitiveness_metrics=competitiveness_metrics,
                market_share_estimate=market_share_estimate,
                positioning_analysis=positioning_analysis,
                recommendations=recommendations,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error analyzing auction competitiveness: {e}")
            raise
    
    async def analyze_account_spend_efficiency(
        self, 
        request: AccountSpendEfficiencyRequest
    ) -> AccountSpendEfficiencyResponse:
        """
        Holistic account-level spend efficiency analysis.
        
        Provides account-wide efficiency metrics and portfolio rebalancing recommendations.
        """
        try:
            # Get account-level insights
            insights = await self.client.get(
                f"{request.ad_account_id}/insights",
                params={
                    "time_range": request.time_range,
                    "fields": "spend,conversions,conversion_values,cpa,roas",
                    "level": "account"
                }
            )
            
            account_data = insights.get("data", [{}])[0]
            
            # Get campaign-level data for contribution analysis
            campaigns_insights = await self.client.get(
                f"{request.ad_account_id}/insights",
                params={
                    "time_range": request.time_range,
                    "fields": "campaign_name,spend,conversions,roas",
                    "level": "campaign",
                    "limit": "100"
                }
            )
            
            campaigns = campaigns_insights.get("data", [])
            
            # Calculate account-wide metrics
            account_metrics = {
                "total_spend": float(account_data.get("spend", 0)),
                "total_conversions": int(account_data.get("conversions", 0)),
                "overall_cpa": float(account_data.get("cpa", 0)),
                "overall_roas": float(account_data.get("roas", 0)),
                "total_revenue": float(account_data.get("conversion_values", 0)),
                "efficiency_score": self._calculate_account_efficiency_score(account_data)
            }
            
            # Analyze campaign contributions
            campaign_contributions = []
            for campaign in campaigns:
                contribution = {
                    "campaign_name": campaign.get("campaign_name", "Unknown"),
                    "spend": float(campaign.get("spend", 0)),
                    "spend_percentage": round((float(campaign.get("spend", 0)) / account_metrics["total_spend"] * 100), 2) if account_metrics["total_spend"] > 0 else 0,
                    "conversions": int(campaign.get("conversions", 0)),
                    "conversion_percentage": round((int(campaign.get("conversions", 0)) / account_metrics["total_conversions"] * 100), 2) if account_metrics["total_conversions"] > 0 else 0,
                    "roas": float(campaign.get("roas", 0)),
                    "contribution_score": self._calculate_contribution_score(campaign, account_metrics)
                }
                campaign_contributions.append(contribution)
            
            # Sort by contribution score
            campaign_contributions.sort(key=lambda x: x["contribution_score"], reverse=True)
            
            # Identify underutilized budget
            underutilized_budget = self._identify_underutilized_budget(
                account_metrics, campaigns
            )
            
            # Generate portfolio rebalancing plan
            rebalancing_plan = self._generate_portfolio_rebalancing(
                campaign_contributions, account_metrics
            )
            
            # Generate recommendations
            recommendations = self._generate_account_efficiency_recommendations(
                account_metrics, campaign_contributions, underutilized_budget, rebalancing_plan
            )
            
            return AccountSpendEfficiencyResponse(
                account_metrics=account_metrics,
                campaign_contributions=campaign_contributions,
                underutilized_budget=underutilized_budget,
                rebalancing_plan=rebalancing_plan,
                recommendations=recommendations,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error analyzing account spend efficiency: {e}")
            raise
    
    async def optimize_profit_margin(
        self, 
        request: ProfitMarginRequest
    ) -> ProfitMarginResponse:
        """
        True profitability analysis with COGS consideration.
        
        Calculates contribution margin and provides profit-maximizing recommendations.
        """
        try:
            # Get revenue and spend data
            insights = await self.client.get(
                f"{request.entity_id}/insights",
                params={
                    "time_range": request.time_range,
                    "fields": "spend,conversions,conversion_values,roas",
                    "level": request.entity_type
                }
            )
            
            data = insights.get("data", [{}])[0]
            
            # Calculate profit metrics
            total_revenue = float(data.get("conversion_values", 0))
            total_spend = float(data.get("spend", 0))
            total_cogs = total_revenue * (request.cogs_percentage / 100)
            
            profit_metrics = {
                "total_revenue": round(total_revenue, 2),
                "total_ad_spend": round(total_spend, 2),
                "total_cogs": round(total_cogs, 2),
                "gross_profit": round(total_revenue - total_cogs, 2),
                "net_profit": round(total_revenue - total_cogs - total_spend, 2),
                "profit_margin_percentage": round(((total_revenue - total_cogs - total_spend) / total_revenue * 100), 2) if total_revenue > 0 else 0,
                "contribution_margin": round(((total_revenue - total_cogs) / total_revenue * 100), 2) if total_revenue > 0 else 0
            }
            
            # Calculate breakeven analysis
            breakeven_analysis = {
                "breakeven_roas": round((1 + request.cogs_percentage / 100), 2),
                "current_roas": float(data.get("roas", 0)),
                "distance_from_breakeven": round(float(data.get("roas", 0)) - (1 + request.cogs_percentage / 100), 2),
                "is_profitable": profit_metrics["net_profit"] > 0,
                "profitability_ratio": round(profit_metrics["net_profit"] / total_spend, 2) if total_spend > 0 else 0
            }
            
            # Calculate profit-maximizing scenarios
            profit_scenarios = self._calculate_profit_scenarios(
                profit_metrics, breakeven_analysis, request.cogs_percentage
            )
            
            # Generate recommendations
            recommendations = self._generate_profit_recommendations(
                profit_metrics, breakeven_analysis, profit_scenarios
            )
            
            return ProfitMarginResponse(
                profit_metrics=profit_metrics,
                breakeven_analysis=breakeven_analysis,
                profit_scenarios=profit_scenarios,
                recommendations=recommendations,
                time_range=request.time_range,
                generated_at=datetime.utcnow()
            )
            
        except Exception as e:
            logger.error(f"Error optimizing profit margin: {e}")
            raise
    
    # Helper methods
    
    def _calculate_marginal_efficiency(self, marginal_cpa: float, average_cpa: float) -> float:
        """Calculate efficiency score for marginal CPA"""
        if average_cpa == 0:
            return 1.0
        return round(average_cpa / marginal_cpa, 2)
    
    def _find_diminishing_returns_threshold(self, analysis: List[Dict]) -> Dict:
        """Find the spend level where diminishing returns begin"""
        if not analysis:
            return {"spend_level": 0, "marginal_cpa": 0}
        
        # Find where marginal CPA exceeds average CPA by 50%
        for entry in analysis:
            if entry["marginal_cpa"] > entry["average_cpa"] * 1.5:
                return {
                    "spend_level": entry["spend_level"],
                    "marginal_cpa": entry["marginal_cpa"],
                    "average_cpa": entry["average_cpa"]
                }
        
        # If no diminishing returns found, return highest spend level
        return {
            "spend_level": analysis[-1]["spend_level"],
            "marginal_cpa": analysis[-1]["marginal_cpa"],
            "average_cpa": analysis[-1]["average_cpa"]
        }
    
    def _calculate_optimal_spend_level(self, analysis: List[Dict], target_cpa: Optional[float]) -> Dict:
        """Calculate optimal spend level based on target CPA"""
        if not analysis or not target_cpa:
            return {"spend_level": 0, "expected_conversions": 0}
        
        # Find highest spend level where CPA <= target
        optimal = None
        for entry in analysis:
            if entry["average_cpa"] <= target_cpa:
                optimal = entry
        
        if optimal:
            return {
                "spend_level": optimal["spend_level"],
                "expected_conversions": optimal["conversions"],
                "expected_cpa": optimal["average_cpa"]
            }
        
        return {"spend_level": analysis[0]["spend_level"], "expected_conversions": analysis[0]["conversions"]}
    
    def _generate_marginal_cpa_recommendations(
        self, analysis: List[Dict], threshold: Dict, optimal: Dict, target_cpa: Optional[float]
    ) -> List[Dict]:
        """Generate recommendations based on marginal CPA analysis"""
        recommendations = []
        
        if threshold.get("spend_level"):
            recommendations.append({
                "priority": "high",
                "action": f"Cap daily spend at ${threshold['spend_level']:.2f}",
                "rationale": f"Diminishing returns begin at this level (marginal CPA: ${threshold['marginal_cpa']:.2f})"
            })
        
        if optimal.get("spend_level") and target_cpa:
            recommendations.append({
                "priority": "medium",
                "action": f"Target ${optimal['spend_level']:.2f} daily spend for optimal CPA",
                "expected_result": f"{optimal['expected_conversions']} conversions at ${optimal.get('expected_cpa', 0):.2f} CPA"
            })
        
        return recommendations
    
    def _create_segment_id(self, segment: Dict) -> str:
        """Create unique segment identifier"""
        parts = []
        if segment.get("age"):
            parts.append(f"age:{segment['age']}")
        if segment.get("gender"):
            parts.append(f"gender:{segment['gender']}")
        if segment.get("publisher_platform"):
            parts.append(f"platform:{segment['publisher_platform']}")
        if segment.get("hourly_stats_aggregated_by_advertiser_time_zone"):
            parts.append(f"hour:{segment['hourly_stats_aggregated_by_advertiser_time_zone']}")
        
        return "_".join(parts) if parts else "unknown"
    
    def _calculate_waste_severity(self, spend: float, conversions: int, roas: float) -> str:
        """Calculate severity of wasted spend"""
        if conversions == 0 and spend > 100:
            return "critical"
        elif conversions == 0 and spend > 50:
            return "high"
        elif roas < 0.5:
            return "high"
        elif roas < 1.0:
            return "medium"
        else:
            return "low"
    
    def _generate_reallocation_plan(self, wasted_segments: List[Dict], total_wasted: float) -> Dict:
        """Generate budget reallocation plan"""
        return {
            "reallocate_from": [s["segment_id"] for s in wasted_segments[:5]],
            "amount_to_reallocate": round(total_wasted * 0.8, 2),  # 80% of wasted spend
            "reallocate_to": "high_performing_segments",
            "expected_improvement": "25-40% efficiency gain"
        }
    
    def _generate_wasted_spend_recommendations(
        self, segments: List[Dict], total: float, reallocation: Dict
    ) -> List[Dict]:
        """Generate wasted spend recommendations"""
        recommendations = []
        
        if total > 100:
            recommendations.append({
                "priority": "critical",
                "action": f"Stop spending on {len(segments[:5])} worst segments immediately",
                "potential_savings": f"${total * 0.5:.2f} per period"
            })
        
        recommendations.append({
            "priority": "high",
            "action": "Implement reallocation plan",
            "details": reallocation
        })
        
        return recommendations
    
    def _calculate_campaign_efficiency_score(self, campaign: Dict) -> float:
        """Calculate overall efficiency score for campaign"""
        roas = float(campaign.get("roas", 0))
        ctr = float(campaign.get("ctr", 0))
        conversions = int(campaign.get("conversions", 0))
        spend = float(campaign.get("spend", 1))
        
        # Weighted efficiency score
        efficiency = (
            roas * 0.5 +
            (conversions / spend) * 100 * 0.3 +
            ctr * 10 * 0.2
        )
        
        return round(efficiency, 2)
    
    def _determine_efficiency_tier(self, score: float) -> str:
        """Determine efficiency tier"""
        if score >= 4.0:
            return "excellent"
        elif score >= 3.0:
            return "good"
        elif score >= 2.0:
            return "fair"
        else:
            return "poor"
    
    def _calculate_roi_contribution(self, campaign: Dict, all_campaigns: List[Dict]) -> float:
        """Calculate campaign's contribution to overall ROI"""
        campaign_revenue = float(campaign.get("roas", 0)) * float(campaign.get("spend", 0))
        total_revenue = sum(float(c.get("roas", 0)) * float(c.get("spend", 0)) for c in all_campaigns)
        
        if total_revenue == 0:
            return 0.0
        
        return round((campaign_revenue / total_revenue * 100), 2)
    
    def _model_budget_reallocation(self, campaigns: List[Dict], total_budget: float) -> Dict:
        """Model optimal budget reallocation"""
        # Allocate based on efficiency scores
        total_efficiency = sum(c["efficiency_score"] for c in campaigns)
        
        allocations = []
        for campaign in campaigns:
            weight = campaign["efficiency_score"] / total_efficiency if total_efficiency > 0 else 1 / len(campaigns)
            new_budget = total_budget * weight
            
            allocations.append({
                "campaign_name": campaign["campaign_name"],
                "current_budget": campaign["spend"],
                "recommended_budget": round(new_budget, 2),
                "change_amount": round(new_budget - campaign["spend"], 2),
                "change_percentage": round(((new_budget - campaign["spend"]) / campaign["spend"] * 100), 2) if campaign["spend"] > 0 else 0
            })
        
        return {"allocations": allocations}
    
    def _calculate_portfolio_metrics(self, campaigns: List[Dict]) -> Dict:
        """Calculate overall portfolio metrics"""
        total_spend = sum(c["spend"] for c in campaigns)
        total_conversions = sum(c["conversions"] for c in campaigns)
        
        weighted_roas = sum(c["roas"] * (c["spend"] / total_spend) for c in campaigns) if total_spend > 0 else 0
        
        return {
            "total_campaigns": len(campaigns),
            "total_spend": round(total_spend, 2),
            "total_conversions": total_conversions,
            "weighted_roas": round(weighted_roas, 2),
            "portfolio_efficiency": statistics.mean([c["efficiency_score"] for c in campaigns]) if campaigns else 0
        }
    
    def _generate_cross_campaign_recommendations(
        self, campaigns: List[Dict], reallocation: Dict, portfolio: Dict
    ) -> List[Dict]:
        """Generate cross-campaign recommendations"""
        recommendations = []
        
        # Identify top and bottom performers
        top_performers = [c for c in campaigns if c["efficiency_tier"] == "excellent"]
        poor_performers = [c for c in campaigns if c["efficiency_tier"] == "poor"]
        
        if poor_performers:
            recommendations.append({
                "priority": "high",
                "action": f"Pause or optimize {len(poor_performers)} poor-performing campaigns",
                "campaigns": [c["campaign_name"] for c in poor_performers]
            })
        
        if top_performers:
            recommendations.append({
                "priority": "high",
                "action": f"Scale {len(top_performers)} top-performing campaigns",
                "expected_lift": "30-50% overall account improvement"
            })
        
        return recommendations
    
    def _calculate_trend_direction(self, values: List[float]) -> str:
        """Calculate trend direction"""
        if len(values) < 2:
            return "stable"
        
        first_half = statistics.mean(values[:len(values)//2])
        second_half = statistics.mean(values[len(values)//2:])
        
        if second_half > first_half * 1.1:
            return "increasing"
        elif second_half < first_half * 0.9:
            return "decreasing"
        else:
            return "stable"
    
    def _calculate_trend_strength(self, values: List[float]) -> float:
        """Calculate trend strength (0-1)"""
        if len(values) < 2:
            return 0.0
        
        # Simple linear regression slope as strength indicator
        n = len(values)
        x = list(range(n))
        x_mean = statistics.mean(x)
        y_mean = statistics.mean(values)
        
        numerator = sum((x[i] - x_mean) * (values[i] - y_mean) for i in range(n))
        denominator = sum((x[i] - x_mean) ** 2 for i in range(n))
        
        if denominator == 0:
            return 0.0
        
        slope = numerator / denominator
        normalized_slope = abs(slope) / y_mean if y_mean != 0 else 0
        
        return min(1.0, normalized_slope)
    
    def _calculate_payback_period(self, cac: float, ltv: float, margin: float) -> Dict:
        """Calculate customer payback period"""
        gross_profit_per_customer = ltv * (margin / 100)
        
        if gross_profit_per_customer == 0:
            return {"payback_months": 999, "payback_achieved": False}
        
        payback_ratio = cac / gross_profit_per_customer
        payback_months = payback_ratio * 12  # Assume 1 year to full LTV
        
        return {
            "payback_months": round(payback_months, 1),
            "payback_achieved": payback_ratio <= 1.0,
            "payback_ratio": round(payback_ratio, 2),
            "gross_profit_per_customer": round(gross_profit_per_customer, 2)
        }
    
    def _calculate_profitability_threshold(self, ltv: float, margin: float) -> Dict:
        """Calculate profitability threshold"""
        max_acceptable_cac = ltv * (margin / 100)
        
        return {
            "max_acceptable_cac": round(max_acceptable_cac, 2),
            "target_cac": round(max_acceptable_cac * 0.7, 2),  # 30% buffer
            "break_even_cac": round(ltv * (margin / 100), 2)
        }
    
    def _generate_cac_recommendations(
        self, trend: Dict, payback: Dict, threshold: Dict
    ) -> List[Dict]:
        """Generate CAC optimization recommendations"""
        recommendations = []
        
        if not payback["payback_achieved"]:
            recommendations.append({
                "priority": "critical",
                "action": f"Reduce CAC below ${threshold['max_acceptable_cac']:.2f}",
                "rationale": "Current CAC exceeds profitability threshold"
            })
        
        if trend["trend_direction"] == "increasing":
            recommendations.append({
                "priority": "high",
                "action": "Investigate rising CAC trend",
                "suggestion": "Review audience targeting and creative performance"
            })
        
        return recommendations
    
    def _predict_budget_exhaustion(
        self, campaign_info: Dict, pacing: Dict, daily_spend: List[Dict]
    ) -> Dict:
        """Predict when budget will be exhausted"""
        lifetime_budget = float(campaign_info.get("lifetime_budget", 0))
        budget_remaining = float(campaign_info.get("budget_remaining", 0))
        
        if lifetime_budget == 0 or budget_remaining == 0:
            return {"exhaustion_date": None, "days_remaining": 999}
        
        avg_daily_spend = pacing["average_daily_spend"]
        days_remaining = budget_remaining / avg_daily_spend if avg_daily_spend > 0 else 999
        
        return {
            "budget_remaining": round(budget_remaining, 2),
            "days_remaining": int(days_remaining),
            "exhaustion_date": (datetime.utcnow() + timedelta(days=days_remaining)).strftime("%Y-%m-%d") if days_remaining < 999 else None,
            "on_track": True if 80 <= pacing["pacing_percentage"] <= 120 else False
        }
    
    def _calculate_optimal_daily_budget(
        self, campaign_info: Dict, pacing: Dict, exhaustion: Dict
    ) -> Dict:
        """Calculate optimal daily budget"""
        current_daily = float(campaign_info.get("daily_budget", 0))
        
        if pacing["pacing_percentage"] < 80:
            recommended = current_daily * 1.25  # Increase 25%
        elif pacing["pacing_percentage"] > 120:
            recommended = current_daily * 0.85  # Decrease 15%
        else:
            recommended = current_daily
        
        return {
            "current_daily_budget": round(current_daily, 2),
            "recommended_daily_budget": round(recommended, 2),
            "change_percentage": round(((recommended - current_daily) / current_daily * 100), 2) if current_daily > 0 else 0
        }
    
    def _generate_pacing_recommendations(
        self, issues: List[Dict], pacing: Dict, optimal: Dict
    ) -> List[Dict]:
        """Generate pacing recommendations"""
        recommendations = []
        
        for issue in issues:
            if issue["issue"] == "underspend":
                recommendations.append({
                    "priority": issue["severity"],
                    "action": f"Increase daily budget to ${optimal['recommended_daily_budget']:.2f}",
                    "rationale": issue["description"]
                })
            elif issue["issue"] == "overspend":
                recommendations.append({
                    "priority": issue["severity"],
                    "action": f"Decrease daily budget to ${optimal['recommended_daily_budget']:.2f}",
                    "rationale": issue["description"]
                })
        
        return recommendations
    
    def _calculate_value_optimization_effectiveness(self, metrics: Dict, target_roas: float) -> float:
        """Calculate value optimization effectiveness"""
        actual_roas = metrics["overall_roas"]
        
        if target_roas == 0:
            return 0.0
        
        effectiveness = (actual_roas / target_roas)
        return round(min(1.0, effectiveness), 2)
    
    def _calculate_ltv_alignment(self, aov: float, ltv: float) -> float:
        """Calculate alignment between AOV and LTV"""
        if ltv == 0:
            return 0.0
        
        alignment = aov / ltv
        return round(alignment, 2)
    
    def _compare_bid_strategies(self, metrics: Dict, current_strategy: str) -> List[Dict]:
        """Compare different bid strategies"""
        # Simplified comparison
        strategies = [
            {"strategy": "LOWEST_COST_WITHOUT_CAP", "estimated_roas": metrics["overall_roas"] * 0.9, "estimated_volume": "+30%"},
            {"strategy": "LOWEST_COST_WITH_BID_CAP", "estimated_roas": metrics["overall_roas"] * 1.0, "estimated_volume": "0%"},
            {"strategy": "COST_CAP", "estimated_roas": metrics["overall_roas"] * 1.1, "estimated_volume": "-10%"},
            {"strategy": "VALUE_OPTIMIZATION", "estimated_roas": metrics["overall_roas"] * 1.15, "estimated_volume": "-15%"}
        ]
        
        return [s for s in strategies if s["strategy"] != current_strategy]
    
    def _generate_value_bidding_recommendations(
        self, metrics: Dict, analysis: Dict, comparison: List[Dict], target_roas: float
    ) -> List[Dict]:
        """Generate value bidding recommendations"""
        recommendations = []
        
        if analysis["roas_vs_target"] < 0:
            recommendations.append({
                "priority": "high",
                "action": "Consider switching to COST_CAP bid strategy",
                "rationale": f"Current ROAS ({metrics['overall_roas']:.2f}) below target ({target_roas:.2f})"
            })
        
        # Recommend best alternative strategy
        best_strategy = max(comparison, key=lambda x: x["estimated_roas"])
        recommendations.append({
            "priority": "medium",
            "action": f"Test {best_strategy['strategy']} bid strategy",
            "expected_improvement": f"{(best_strategy['estimated_roas'] / metrics['overall_roas'] - 1) * 100:.1f}% ROAS improvement"
        })
        
        return recommendations
    
    def _calculate_efficiency_at_volume(self, data_point: Dict) -> float:
        """Calculate efficiency score at given volume"""
        conversions = int(data_point.get("conversions", 0))
        roas = float(data_point.get("roas", 0))
        
        # Combined score: volume * efficiency
        return conversions * roas / 100
    
    def _find_optimal_balance_point(self, curve: List[Dict], priority: str) -> Dict:
        """Find optimal balance between volume and efficiency"""
        if not curve:
            return {}
        
        if priority == "volume":
            # Maximize conversions while maintaining decent efficiency
            valid = [p for p in curve if p["efficiency_score"] > 0.5]
            return max(valid, key=lambda x: x["conversions"]) if valid else curve[-1]
        elif priority == "efficiency":
            # Maximize efficiency while maintaining decent volume
            return max(curve, key=lambda x: x["efficiency_score"])
        else:  # balanced
            # Maximize combined score
            return max(curve, key=lambda x: x["efficiency_score"])
    
    def _estimate_growth_ceiling(self, curve: List[Dict]) -> int:
        """Estimate maximum achievable conversions"""
        if not curve:
            return 0
        
        return max(p["conversions"] for p in curve) * 2  # Simplified estimate
    
    def _estimate_efficiency_at_scale(self, curve: List[Dict], multiplier: float) -> float:
        """Estimate efficiency at scaled volume"""
        if not curve:
            return 0.0
        
        current_max = max(p["conversions"] for p in curve)
        current_max * multiplier
        
        # Assume 10% efficiency loss per doubling
        efficiency_degradation = (multiplier - 1) * 0.1
        current_roas = statistics.mean([p["roas"] for p in curve if p["roas"] > 0])
        
        return round(current_roas * (1 - efficiency_degradation), 2)
    
    def _generate_tradeoff_recommendations(
        self, curve: List[Dict], optimal: Dict, analysis: Dict, priority: str
    ) -> List[Dict]:
        """Generate quality vs quantity recommendations"""
        recommendations = []
        
        if priority == "volume":
            recommendations.append({
                "priority": "high",
                "action": "Expand audience targeting for volume growth",
                "expected_result": f"Up to {analysis['growth_ceiling']} conversions achievable"
            })
        elif priority == "efficiency":
            recommendations.append({
                "priority": "high",
                "action": "Tighten targeting and increase quality thresholds",
                "expected_result": "10-20% efficiency improvement"
            })
        
        return recommendations
    
    def _estimate_auction_density(self, data: Dict) -> str:
        """Estimate auction density level"""
        competitiveness = float(data.get("auction_competitiveness", 0))
        
        if competitiveness > 0.8:
            return "very_high"
        elif competitiveness > 0.6:
            return "high"
        elif competitiveness > 0.4:
            return "medium"
        else:
            return "low"
    
    def _calculate_competitive_pressure(self, data: Dict) -> float:
        """Calculate competitive bid pressure"""
        cpm = float(data.get("cpm", 0))
        # Normalize CPM to 0-1 scale (assuming $50 CPM is very high)
        return min(1.0, cpm / 50)
    
    def _estimate_market_saturation(self, data: Dict) -> float:
        """Estimate market saturation level"""
        frequency = float(data.get("frequency", 0))
        # High frequency suggests market saturation
        return min(1.0, frequency / 10)
    
    def _estimate_market_share(self, data: Dict, metrics: Dict) -> Dict:
        """Estimate market share"""
        impressions = int(data.get("impressions", 0))
        estimated_total_market = impressions / metrics["win_rate_estimate"] if metrics["win_rate_estimate"] > 0 else 0
        
        return {
            "estimated_impressions": impressions,
            "estimated_total_market": int(estimated_total_market),
            "share_of_voice": round(metrics["win_rate_estimate"] * 100, 2)
        }
    
    def _determine_competitive_position(self, metrics: Dict) -> str:
        """Determine competitive position"""
        if metrics["auction_competitiveness_score"] > 0.8:
            return "market_leader"
        elif metrics["auction_competitiveness_score"] > 0.6:
            return "strong_competitor"
        elif metrics["auction_competitiveness_score"] > 0.4:
            return "moderate_player"
        else:
            return "weak_position"
    
    def _calculate_relative_bid_strength(self, data: Dict) -> float:
        """Calculate relative bid strength"""
        # Simplified - would compare to market benchmarks
        return 0.75
    
    def _identify_competitive_threats(self, metrics: Dict) -> List[str]:
        """Identify competitive threats"""
        threats = []
        
        if metrics["auction_competitiveness_score"] > 0.7:
            threats.append("high_competitive_pressure")
        if metrics["market_saturation_level"] > 0.7:
            threats.append("market_saturation")
        if metrics["competitive_bid_pressure"] > 0.6:
            threats.append("rising_cpms")
        
        return threats if threats else ["none_detected"]
    
    def _generate_competitiveness_recommendations(
        self, metrics: Dict, positioning: Dict, market_share: Dict
    ) -> List[Dict]:
        """Generate competitiveness recommendations"""
        recommendations = []
        
        if positioning["current_position"] in ["weak_position", "moderate_player"]:
            recommendations.append({
                "priority": "high",
                "action": "Increase bid amounts by 15-25% to improve competitive position",
                "rationale": f"Current position: {positioning['current_position']}"
            })
        
        if "market_saturation" in positioning["competitive_threats"]:
            recommendations.append({
                "priority": "medium",
                "action": "Expand to new audience segments",
                "rationale": "High market saturation detected in current targeting"
            })
        
        return recommendations
    
    def _calculate_account_efficiency_score(self, data: Dict) -> float:
        """Calculate account-level efficiency score"""
        roas = float(data.get("roas", 0))
        cpa = float(data.get("cpa", 1))
        
        # Simplified efficiency score
        return round(roas / (cpa / 10), 2)
    
    def _calculate_contribution_score(self, campaign: Dict, account_metrics: Dict) -> float:
        """Calculate campaign contribution score"""
        campaign_revenue = float(campaign.get("roas", 0)) * float(campaign.get("spend", 0))
        campaign_spend_pct = float(campaign.get("spend", 0)) / account_metrics["total_spend"] if account_metrics["total_spend"] > 0 else 0
        
        # Campaigns with high revenue relative to spend percentage score higher
        if campaign_spend_pct == 0:
            return 0.0
        
        revenue_efficiency = campaign_revenue / (campaign_spend_pct * account_metrics["total_spend"])
        return round(revenue_efficiency, 2)
    
    def _identify_underutilized_budget(self, account_metrics: Dict, campaigns: List[Dict]) -> Dict:
        """Identify underutilized budget opportunities"""
        # Simplified - would analyze delivery data
        return {
            "underutilized_amount": 0,
            "underutilized_percentage": 0,
            "opportunity": "No significant underutilization detected"
        }
    
    def _generate_portfolio_rebalancing(self, campaigns: List[Dict], account_metrics: Dict) -> Dict:
        """Generate portfolio rebalancing recommendations"""
        # Move budget from low performers to high performers
        low_performers = [c for c in campaigns if c["contribution_score"] < 0.8]
        high_performers = [c for c in campaigns if c["contribution_score"] > 1.2]
        
        rebalancing_actions = []
        
        for low_perf in low_performers[:3]:
            rebalancing_actions.append({
                "from_campaign": low_perf["campaign_name"],
                "to_campaigns": [h["campaign_name"] for h in high_performers[:2]],
                "amount": round(low_perf["spend"] * 0.3, 2),
                "rationale": "Low contribution score"
            })
        
        return {"actions": rebalancing_actions}
    
    def _generate_account_efficiency_recommendations(
        self, metrics: Dict, campaigns: List[Dict], underutilized: Dict, rebalancing: Dict
    ) -> List[Dict]:
        """Generate account-level efficiency recommendations"""
        recommendations = []
        
        # Identify campaigns to optimize
        poor_campaigns = [c for c in campaigns if c["conversion_percentage"] < c["spend_percentage"] * 0.7]
        
        if poor_campaigns:
            recommendations.append({
                "priority": "high",
                "action": f"Optimize or pause {len(poor_campaigns)} underperforming campaigns",
                "campaigns": [c["campaign_name"] for c in poor_campaigns[:3]]
            })
        
        # Budget reallocation
        if rebalancing["actions"]:
            recommendations.append({
                "priority": "high",
                "action": "Implement portfolio rebalancing plan",
                "expected_improvement": "15-25% overall efficiency gain"
            })
        
        return recommendations
    
    def _calculate_profit_scenarios(
        self, metrics: Dict, breakeven: Dict, cogs_pct: float
    ) -> List[Dict]:
        """Calculate different profit scenarios"""
        scenarios = []
        
        # Current scenario
        scenarios.append({
            "scenario": "current",
            "roas": breakeven["current_roas"],
            "net_profit": metrics["net_profit"],
            "profit_margin": metrics["profit_margin_percentage"]
        })
        
        # Optimistic scenario (+20% ROAS)
        optimistic_roas = breakeven["current_roas"] * 1.2
        optimistic_revenue = metrics["total_ad_spend"] * optimistic_roas
        optimistic_cogs = optimistic_revenue * (cogs_pct / 100)
        optimistic_profit = optimistic_revenue - optimistic_cogs - metrics["total_ad_spend"]
        
        scenarios.append({
            "scenario": "optimistic_+20%_roas",
            "roas": round(optimistic_roas, 2),
            "net_profit": round(optimistic_profit, 2),
            "profit_margin": round((optimistic_profit / optimistic_revenue * 100), 2) if optimistic_revenue > 0 else 0
        })
        
        # Conservative scenario (-10% ROAS)
        conservative_roas = breakeven["current_roas"] * 0.9
        conservative_revenue = metrics["total_ad_spend"] * conservative_roas
        conservative_cogs = conservative_revenue * (cogs_pct / 100)
        conservative_profit = conservative_revenue - conservative_cogs - metrics["total_ad_spend"]
        
        scenarios.append({
            "scenario": "conservative_-10%_roas",
            "roas": round(conservative_roas, 2),
            "net_profit": round(conservative_profit, 2),
            "profit_margin": round((conservative_profit / conservative_revenue * 100), 2) if conservative_revenue > 0 else 0
        })
        
        return scenarios
    
    def _generate_profit_recommendations(
        self, metrics: Dict, breakeven: Dict, scenarios: List[Dict]
    ) -> List[Dict]:
        """Generate profit optimization recommendations"""
        recommendations = []
        
        if not breakeven["is_profitable"]:
            recommendations.append({
                "priority": "critical",
                "action": f"Improve ROAS to at least {breakeven['breakeven_roas']:.2f} to achieve profitability",
                "current_roas": breakeven["current_roas"],
                "required_improvement": f"{((breakeven['breakeven_roas'] / breakeven['current_roas'] - 1) * 100):.1f}%"
            })
        
        if metrics["profit_margin_percentage"] < 20:
            recommendations.append({
                "priority": "high",
                "action": "Focus on margin improvement - target 20%+ profit margin",
                "suggestions": ["Reduce COGS", "Increase average order value", "Improve ROAS"]
            })
        
        return recommendations


# Singleton instance
_engine_instance = None


def get_cost_efficiency_analysis_engine() -> CostEfficiencyAnalysisEngine:
    """Get or create the cost efficiency analysis engine instance"""
    global _engine_instance
    if _engine_instance is None:
        from .meta_client import get_client
        _engine_instance = CostEfficiencyAnalysisEngine(get_client())
    return _engine_instance

