"""
Competitive Analysis Result Data Models

Extends base analysis results with competitive intelligence metadata.
"""

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

from ...intelligence_aggregator import AnalysisResult


class CompetitorCategory(Enum):
    """Competitor categorization for analysis context"""
    EDUCATIONAL_TECHNICAL = "educational_technical"
    EDUCATIONAL_GENERAL = "educational_general"
    EDUCATIONAL_SPECIALIZED = "educational_specialized"
    INDUSTRY_NEWS = "industry_news"
    SERVICE_PROVIDER = "service_provider"
    MANUFACTURER = "manufacturer"


class CompetitorPriority(Enum):
    """Strategic priority level for competitive analysis"""
    HIGH = "high"
    MEDIUM = "medium"
    LOW = "low"


class MarketPosition(Enum):
    """Market position classification for competitors"""
    LEADER = "leader"
    CHALLENGER = "challenger" 
    FOLLOWER = "follower"
    NICHE = "niche"


@dataclass
class MarketContext:
    """Market positioning context for competitive content"""
    category: CompetitorCategory
    priority: CompetitorPriority
    target_audience: str
    content_focus_areas: List[str] = field(default_factory=list)
    competitive_advantages: List[str] = field(default_factory=list)
    analysis_focus: List[str] = field(default_factory=list)
    
    # Channel/profile metrics
    subscribers: Optional[int] = None
    total_videos: Optional[int] = None  
    total_views: Optional[int] = None
    avg_views_per_video: Optional[float] = None
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for JSON serialization"""
        return {
            'category': self.category.value,
            'priority': self.priority.value,
            'target_audience': self.target_audience,
            'content_focus_areas': self.content_focus_areas,
            'competitive_advantages': self.competitive_advantages,
            'analysis_focus': self.analysis_focus,
            'subscribers': self.subscribers,
            'total_videos': self.total_videos,
            'total_views': self.total_views,
            'avg_views_per_video': self.avg_views_per_video
        }


@dataclass
class CompetitiveAnalysisResult(AnalysisResult):
    """
    Extends base analysis result with competitive intelligence metadata.
    
    Adds competitor context, market positioning, and comparative performance metrics.
    """
    competitor_name: str = ""
    competitor_platform: str = ""  # youtube, instagram, blog
    competitor_key: str = ""  # Internal identifier (e.g., 'ac_service_tech')
    market_context: Optional[MarketContext] = None
    
    # Competitive performance metrics
    competitive_ranking: Optional[int] = None
    performance_vs_hkia: Optional[float] = None
    content_quality_score: Optional[float] = None
    engagement_vs_category_avg: Optional[float] = None
    
    # Content strategic analysis
    content_focus_tags: List[str] = field(default_factory=list)
    strategic_importance: Optional[str] = None  # high, medium, low
    content_gap_indicator: bool = False
    
    # Timing and publishing analysis
    days_since_publish: Optional[int] = None
    publishing_frequency_context: Optional[str] = None
    
    def to_competitive_dict(self) -> Dict[str, Any]:
        """Convert to dictionary with competitive intelligence focus"""
        base_dict = self.to_dict()
        
        competitive_dict = {
            **base_dict,
            'competitor_name': self.competitor_name,
            'competitor_platform': self.competitor_platform,
            'competitor_key': self.competitor_key,
            'market_context': self.market_context.to_dict(),
            'competitive_ranking': self.competitive_ranking,
            'performance_vs_hkia': self.performance_vs_hkia,
            'content_quality_score': self.content_quality_score,
            'engagement_vs_category_avg': self.engagement_vs_category_avg,
            'content_focus_tags': self.content_focus_tags,
            'strategic_importance': self.strategic_importance,
            'content_gap_indicator': self.content_gap_indicator,
            'days_since_publish': self.days_since_publish,
            'publishing_frequency_context': self.publishing_frequency_context
        }
        
        return competitive_dict
    
    def get_competitive_summary(self) -> Dict[str, Any]:
        """Get concise competitive intelligence summary"""
        # Safely extract primary topic from claude_analysis
        topic_primary = None
        if isinstance(self.claude_analysis, dict):
            topic_primary = self.claude_analysis.get('primary_topic')
        
        # Safe engagement rate extraction
        engagement_rate = None
        if isinstance(self.engagement_metrics, dict):
            engagement_rate = self.engagement_metrics.get('engagement_rate')
        
        return {
            'competitor': f"{self.competitor_name} ({self.competitor_platform})",
            'category': self.market_context.category.value if self.market_context else None,
            'priority': self.market_context.priority.value if self.market_context else None,
            'topic_primary': topic_primary,
            'content_focus': self.content_focus_tags[:3],  # Top 3
            'quality_score': self.content_quality_score,
            'engagement_rate': engagement_rate,
            'strategic_importance': self.strategic_importance,
            'content_gap': self.content_gap_indicator,
            'days_old': self.days_since_publish
        }


@dataclass
class CompetitorMetrics:
    """Aggregated performance metrics for a competitor"""
    competitor_name: str
    total_content_pieces: int
    avg_engagement_rate: float
    total_views: int
    content_frequency: float  # posts per week
    top_topics: List[str] = field(default_factory=list)
    content_consistency_score: float = 0.0
    market_position: MarketPosition = MarketPosition.FOLLOWER
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for JSON serialization"""
        return {
            'competitor_name': self.competitor_name,
            'total_content_pieces': self.total_content_pieces,
            'avg_engagement_rate': self.avg_engagement_rate,
            'total_views': self.total_views,
            'content_frequency': self.content_frequency,
            'top_topics': self.top_topics,
            'content_consistency_score': self.content_consistency_score,
            'market_position': self.market_position.value
        }