"""
Content Gap Analysis Data Models

Data structures for identifying strategic content opportunities.
"""

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


class GapType(Enum):
    """Types of content gaps identified"""
    TOPIC_MISSING = "topic_missing"  # HKIA lacks content in this topic
    FORMAT_MISSING = "format_missing"  # HKIA lacks this content format
    FREQUENCY_GAP = "frequency_gap"  # HKIA posts less frequently
    QUALITY_GAP = "quality_gap"  # HKIA content lower quality
    ENGAGEMENT_GAP = "engagement_gap"  # HKIA content gets less engagement
    TIMING_GAP = "timing_gap"  # HKIA misses optimal posting times
    PLATFORM_GAP = "platform_gap"  # HKIA weak on this platform


class OpportunityPriority(Enum):
    """Strategic priority for content opportunities"""
    CRITICAL = "critical"
    HIGH = "high" 
    MEDIUM = "medium"
    LOW = "low"


class ImpactLevel(Enum):
    """Expected impact of addressing content gap"""
    HIGH = "high"
    MEDIUM = "medium" 
    LOW = "low"


@dataclass
class CompetitorExample:
    """Example of successful competitive content"""
    competitor_name: str
    content_title: str
    content_url: str
    engagement_rate: float
    view_count: Optional[int] = None
    publish_date: Optional[datetime] = None
    key_success_factors: List[str] = field(default_factory=list)
    
    def to_dict(self) -> Dict[str, Any]:
        return {
            'competitor_name': self.competitor_name,
            'content_title': self.content_title,
            'content_url': self.content_url,
            'engagement_rate': self.engagement_rate,
            'view_count': self.view_count,
            'publish_date': self.publish_date.isoformat() if self.publish_date else None,
            'key_success_factors': self.key_success_factors
        }


@dataclass
class ContentGap:
    """
    Represents a strategic content opportunity identified through competitive analysis.
    
    Core data structure for content gap analysis and strategic recommendations.
    """
    gap_id: str  # Unique identifier
    topic: str
    gap_type: GapType
    
    # Opportunity scoring
    opportunity_score: float  # 0-1, higher = better opportunity
    priority: OpportunityPriority
    estimated_impact: ImpactLevel
    
    # Strategic analysis
    recommended_action: str
    
    # Supporting evidence
    competitor_examples: List[CompetitorExample] = field(default_factory=list)
    market_evidence: Dict[str, Any] = field(default_factory=dict)
    
    # Optional strategic details
    content_format_suggestion: Optional[str] = None
    target_audience: Optional[str] = None
    optimal_platforms: List[str] = field(default_factory=list)
    
    # Resource requirements
    effort_estimate: Optional[str] = None  # low, medium, high
    required_expertise: List[str] = field(default_factory=list)
    
    # Success metrics
    success_metrics: List[str] = field(default_factory=list)
    benchmark_targets: Dict[str, float] = field(default_factory=dict)
    
    # Metadata
    identified_date: datetime = field(default_factory=datetime.utcnow)
    
    def get_top_competitor_examples(self, limit: int = 3) -> List[CompetitorExample]:
        """Get top performing competitor examples for this gap"""
        return sorted(
            self.competitor_examples, 
            key=lambda x: x.engagement_rate, 
            reverse=True
        )[:limit]
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for JSON serialization"""
        return {
            'gap_id': self.gap_id,
            'topic': self.topic,
            'gap_type': self.gap_type.value,
            'opportunity_score': self.opportunity_score,
            'priority': self.priority.value,
            'estimated_impact': self.estimated_impact.value,
            'competitor_examples': [ex.to_dict() for ex in self.competitor_examples],
            'market_evidence': self.market_evidence,
            'recommended_action': self.recommended_action,
            'content_format_suggestion': self.content_format_suggestion,
            'target_audience': self.target_audience,
            'optimal_platforms': self.optimal_platforms,
            'effort_estimate': self.effort_estimate,
            'required_expertise': self.required_expertise,
            'success_metrics': self.success_metrics,
            'benchmark_targets': self.benchmark_targets,
            'identified_date': self.identified_date.isoformat(),
            'top_competitor_examples': [ex.to_dict() for ex in self.get_top_competitor_examples()]
        }


@dataclass
class ContentOpportunity:
    """
    Strategic content opportunity with actionable recommendations.
    
    Higher-level strategic recommendation based on content gap analysis.
    """
    opportunity_id: str
    title: str
    description: str
    
    # Strategic context
    related_gaps: List[str]  # Gap IDs this opportunity addresses
    market_opportunity: str  # Market context and reasoning
    competitive_advantage: str  # How this helps vs competitors
    
    # Implementation details
    recommended_content_pieces: List[Dict[str, Any]] = field(default_factory=list)
    content_series_potential: bool = False
    cross_platform_strategy: Dict[str, str] = field(default_factory=dict)
    
    # Business impact
    projected_engagement_lift: Optional[float] = None  # % improvement
    projected_traffic_increase: Optional[float] = None  # % improvement 
    revenue_impact_potential: Optional[str] = None  # low, medium, high
    
    # Timeline and resources
    implementation_timeline: Optional[str] = None  # weeks/months
    resource_requirements: Dict[str, str] = field(default_factory=dict)
    dependencies: List[str] = field(default_factory=list)
    
    # Success tracking
    kpi_targets: Dict[str, float] = field(default_factory=dict)
    measurement_strategy: List[str] = field(default_factory=list)
    
    created_date: datetime = field(default_factory=datetime.utcnow)
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for JSON serialization"""
        return {
            'opportunity_id': self.opportunity_id,
            'title': self.title,
            'description': self.description,
            'related_gaps': self.related_gaps,
            'market_opportunity': self.market_opportunity,
            'competitive_advantage': self.competitive_advantage,
            'recommended_content_pieces': self.recommended_content_pieces,
            'content_series_potential': self.content_series_potential,
            'cross_platform_strategy': self.cross_platform_strategy,
            'projected_engagement_lift': self.projected_engagement_lift,
            'projected_traffic_increase': self.projected_traffic_increase,
            'revenue_impact_potential': self.revenue_impact_potential,
            'implementation_timeline': self.implementation_timeline,
            'resource_requirements': self.resource_requirements,
            'dependencies': self.dependencies,
            'kpi_targets': self.kpi_targets,
            'measurement_strategy': self.measurement_strategy,
            'created_date': self.created_date.isoformat()
        }


@dataclass
class GapAnalysisReport:
    """
    Comprehensive content gap analysis report.
    
    Summary of all identified gaps and strategic opportunities.
    """
    report_id: str
    analysis_date: datetime
    timeframe_analyzed: str
    
    # Gap analysis results
    identified_gaps: List[ContentGap] = field(default_factory=list)
    strategic_opportunities: List[ContentOpportunity] = field(default_factory=list)
    
    # Summary insights
    key_findings: List[str] = field(default_factory=list)
    priority_actions: List[str] = field(default_factory=list)
    quick_wins: List[str] = field(default_factory=list)
    
    # Competitive context
    competitor_strengths: Dict[str, List[str]] = field(default_factory=dict)
    hkia_advantages: List[str] = field(default_factory=list)
    market_trends: List[str] = field(default_factory=list)
    
    def get_gaps_by_priority(self, priority: OpportunityPriority) -> List[ContentGap]:
        """Get gaps filtered by priority level"""
        return [gap for gap in self.identified_gaps if gap.priority == priority]
    
    def get_high_impact_opportunities(self) -> List[ContentOpportunity]:
        """Get opportunities with high projected impact"""
        return [
            opp for opp in self.strategic_opportunities 
            if opp.revenue_impact_potential == "high" or opp.projected_engagement_lift and opp.projected_engagement_lift > 0.2
        ]
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary for JSON serialization"""
        return {
            'report_id': self.report_id,
            'analysis_date': self.analysis_date.isoformat(),
            'timeframe_analyzed': self.timeframe_analyzed,
            'identified_gaps': [gap.to_dict() for gap in self.identified_gaps],
            'strategic_opportunities': [opp.to_dict() for opp in self.strategic_opportunities],
            'key_findings': self.key_findings,
            'priority_actions': self.priority_actions,
            'quick_wins': self.quick_wins,
            'competitor_strengths': self.competitor_strengths,
            'hkia_advantages': self.hkia_advantages,
            'market_trends': self.market_trends,
            'critical_gaps': [gap.to_dict() for gap in self.get_gaps_by_priority(OpportunityPriority.CRITICAL)],
            'high_impact_opportunities': [opp.to_dict() for opp in self.get_high_impact_opportunities()]
        }