"""
Comparative Metrics Data Models

Data structures for cross-competitor performance comparison and market analysis.
"""

from dataclasses import dataclass, field
from datetime import datetime
from typing import Dict, List, Optional, Any
from enum import Enum


class TrendDirection(Enum):
    """Trend direction indicators"""
    UP = "up"
    DOWN = "down"
    STABLE = "stable"
    VOLATILE = "volatile"


@dataclass
class ContentPerformance:
    """Performance metrics for content analysis"""
    total_content: int
    avg_engagement_rate: float
    avg_views: float
    avg_quality_score: float
    top_performing_topics: List[str] = field(default_factory=list)
    publishing_frequency: Optional[float] = None  # posts per week
    content_consistency: Optional[float] = None  # score 0-1
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'total_content': self.total_content,
            'avg_engagement_rate': self.avg_engagement_rate,
            'avg_views': self.avg_views,
            'avg_quality_score': self.avg_quality_score,
            'top_performing_topics': self.top_performing_topics,
            'publishing_frequency': self.publishing_frequency,
            'content_consistency': self.content_consistency
        }


@dataclass 
class EngagementComparison:
    """Cross-competitor engagement analysis"""
    hkia_avg_engagement: float
    competitor_engagement: Dict[str, float]
    platform_benchmarks: Dict[str, float]  # Platform averages
    engagement_leaders: List[str]  # Top performers
    engagement_trends: Dict[str, TrendDirection] = field(default_factory=dict)
    
    def get_relative_performance(self, competitor: str) -> Optional[float]:
        """Get competitor engagement relative to HKIA (1.0 = same, 2.0 = 2x better)"""
        if competitor in self.competitor_engagement and self.hkia_avg_engagement > 0:
            return self.competitor_engagement[competitor] / self.hkia_avg_engagement
        return None
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'hkia_avg_engagement': self.hkia_avg_engagement,
            'competitor_engagement': self.competitor_engagement,
            'platform_benchmarks': self.platform_benchmarks,
            'engagement_leaders': self.engagement_leaders,
            'engagement_trends': {k: v.value for k, v in self.engagement_trends.items()}
        }


@dataclass
class TopicMarketShare:
    """Market share analysis by topic"""
    topic: str
    hkia_content_count: int
    competitor_content_counts: Dict[str, int]
    hkia_engagement_share: float
    competitor_engagement_shares: Dict[str, float]
    market_leader: str
    hkia_ranking: int
    
    def get_total_market_content(self) -> int:
        """Total content pieces in this topic across all competitors"""
        return self.hkia_content_count + sum(self.competitor_content_counts.values())
    
    def get_hkia_market_share(self) -> float:
        """HKIA's content share in this topic (0-1)"""
        total = self.get_total_market_content()
        return self.hkia_content_count / total if total > 0 else 0.0
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'topic': self.topic,
            'hkia_content_count': self.hkia_content_count,
            'competitor_content_counts': self.competitor_content_counts,
            'hkia_engagement_share': self.hkia_engagement_share,
            'competitor_engagement_shares': self.competitor_engagement_shares,
            'market_leader': self.market_leader,
            'hkia_ranking': self.hkia_ranking,
            'total_market_content': self.get_total_market_content(),
            'hkia_market_share': self.get_hkia_market_share()
        }


@dataclass
class PublishingIntelligence:
    """Publishing pattern analysis across competitors"""
    hkia_frequency: float  # posts per week
    competitor_frequencies: Dict[str, float]
    optimal_posting_days: List[str]  # Based on engagement data
    optimal_posting_hours: List[int]  # 24-hour format
    seasonal_patterns: Dict[str, float] = field(default_factory=dict)
    consistency_scores: Dict[str, float] = field(default_factory=dict)
    
    def get_frequency_ranking(self) -> List[tuple[str, float]]:
        """Get competitors ranked by publishing frequency"""
        all_frequencies = {
            'hkia': self.hkia_frequency,
            **self.competitor_frequencies
        }
        return sorted(all_frequencies.items(), key=lambda x: x[1], reverse=True)
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'hkia_frequency': self.hkia_frequency,
            'competitor_frequencies': self.competitor_frequencies,
            'optimal_posting_days': self.optimal_posting_days,
            'optimal_posting_hours': self.optimal_posting_hours,
            'seasonal_patterns': self.seasonal_patterns,
            'consistency_scores': self.consistency_scores,
            'frequency_ranking': self.get_frequency_ranking()
        }


@dataclass
class TrendingTopic:
    """Trending topic identification"""
    topic: str
    trend_score: float  # 0-1, higher = more trending
    trend_direction: TrendDirection
    leading_competitor: str
    content_growth_rate: float  # % increase in content
    engagement_growth_rate: float  # % increase in engagement
    time_period: str  # e.g., "last_30_days"
    example_content: List[str] = field(default_factory=list)  # URLs or titles
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'topic': self.topic,
            'trend_score': self.trend_score,
            'trend_direction': self.trend_direction.value,
            'leading_competitor': self.leading_competitor,
            'content_growth_rate': self.content_growth_rate,
            'engagement_growth_rate': self.engagement_growth_rate,
            'time_period': self.time_period,
            'example_content': self.example_content
        }


@dataclass
class ComparativeMetrics:
    """
    Comprehensive cross-competitor performance metrics and market analysis.
    
    Central data structure for Phase 3 competitive intelligence reporting.
    """
    analysis_date: datetime
    timeframe: str  # e.g., "last_30_days", "last_7_days"
    
    # Core performance comparison
    hkia_performance: ContentPerformance
    competitor_performance: Dict[str, ContentPerformance]
    
    # Market share analysis
    market_share_by_topic: Dict[str, TopicMarketShare]
    
    # Engagement analysis
    engagement_comparison: EngagementComparison
    
    # Publishing intelligence  
    publishing_analysis: PublishingIntelligence
    
    # Trending analysis
    trending_topics: List[TrendingTopic] = field(default_factory=list)
    
    # Summary insights
    key_insights: List[str] = field(default_factory=list)
    strategic_recommendations: List[str] = field(default_factory=list)
    
    def get_top_competitors_by_engagement(self, limit: int = 3) -> List[tuple[str, float]]:
        """Get top competitors by average engagement rate"""
        competitors = [
            (name, perf.avg_engagement_rate) 
            for name, perf in self.competitor_performance.items()
        ]
        return sorted(competitors, key=lambda x: x[1], reverse=True)[:limit]
    
    def get_content_gap_topics(self, min_gap_score: float = 0.7) -> List[str]:
        """Get topics where competitors significantly outperform HKIA"""
        gap_topics = []
        for topic, market_share in self.market_share_by_topic.items():
            if (market_share.hkia_ranking > 2 and 
                market_share.get_hkia_market_share() < min_gap_score):
                gap_topics.append(topic)
        return gap_topics
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for JSON serialization"""
        return {
            'analysis_date': self.analysis_date.isoformat(),
            'timeframe': self.timeframe,
            'hkia_performance': self.hkia_performance.to_dict(),
            'competitor_performance': {
                name: perf.to_dict() 
                for name, perf in self.competitor_performance.items()
            },
            'market_share_by_topic': {
                topic: share.to_dict()
                for topic, share in self.market_share_by_topic.items()
            },
            'engagement_comparison': self.engagement_comparison.to_dict(),
            'publishing_analysis': self.publishing_analysis.to_dict(),
            'trending_topics': [topic.to_dict() for topic in self.trending_topics],
            'key_insights': self.key_insights,
            'strategic_recommendations': self.strategic_recommendations,
            'top_competitors_by_engagement': self.get_top_competitors_by_engagement(),
            'content_gap_topics': self.get_content_gap_topics()
        }