"""
Topic opportunity matrix generator for blog content strategy.

Creates comprehensive topic opportunity matrices combining competitive analysis,
content gap analysis, and strategic positioning recommendations.
"""

import logging
from pathlib import Path
from typing import Dict, List, Set, Tuple, Optional
from dataclasses import dataclass, asdict
import json
from datetime import datetime

logger = logging.getLogger(__name__)

@dataclass 
class TopicOpportunity:
    """Represents a specific blog topic opportunity."""
    topic: str
    priority: str  # "high", "medium", "low"
    opportunity_score: float
    competitive_landscape: str  # Description of competitive situation
    recommended_approach: str  # Content strategy recommendation  
    target_keywords: List[str]
    estimated_difficulty: str  # "easy", "moderate", "challenging"
    content_type_suggestions: List[str]  # Types of content to create
    hvacr_school_coverage: str  # How HVACRSchool covers this topic
    market_demand_indicators: Dict[str, any]  # Demand signals
    
@dataclass
class TopicOpportunityMatrix:
    """Complete topic opportunity matrix for blog content strategy."""
    high_priority_opportunities: List[TopicOpportunity]
    medium_priority_opportunities: List[TopicOpportunity] 
    low_priority_opportunities: List[TopicOpportunity]
    content_calendar_suggestions: List[Dict[str, str]]
    strategic_recommendations: List[str]
    competitive_monitoring_topics: List[str]
    
class TopicOpportunityMatrixGenerator:
    """
    Generates comprehensive topic opportunity matrices for blog content planning.
    
    Combines insights from BlogTopicAnalyzer and ContentGapAnalyzer to create
    actionable blog content strategies with specific topic recommendations.
    """
    
    def __init__(self):
        # Content type mapping based on topic characteristics
        self.content_type_map = {
            'troubleshooting': ['How-to Guide', 'Diagnostic Checklist', 'Video Tutorial', 'Case Study'],
            'installation': ['Step-by-Step Guide', 'Installation Checklist', 'Video Walkthrough', 'Code Compliance Guide'],
            'maintenance': ['Maintenance Schedule', 'Preventive Care Guide', 'Seasonal Checklist', 'Best Practices'],
            'electrical': ['Safety Guide', 'Wiring Diagram', 'Testing Procedures', 'Code Requirements'],
            'refrigeration': ['System Guide', 'Diagnostic Procedures', 'Performance Analysis', 'Technical Deep-Dive'],
            'efficiency': ['Performance Guide', 'Energy Audit Process', 'Optimization Tips', 'ROI Calculator'],
            'codes_standards': ['Compliance Guide', 'Code Update Summary', 'Inspection Checklist', 'Certification Prep']
        }
        
        # Difficulty assessment factors
        self.difficulty_factors = {
            'technical_complexity': 0.4,
            'competitive_saturation': 0.3,
            'content_depth_required': 0.2,  
            'regulatory_requirements': 0.1
        }
        
    def generate_matrix(self, topic_analysis, gap_analysis) -> TopicOpportunityMatrix:
        """
        Generate comprehensive topic opportunity matrix.
        
        Args:
            topic_analysis: Results from BlogTopicAnalyzer
            gap_analysis: Results from ContentGapAnalyzer
            
        Returns:
            TopicOpportunityMatrix with prioritized opportunities
        """
        logger.info("Generating topic opportunity matrix...")
        
        # Create topic opportunities from gap analysis
        opportunities = self._create_topic_opportunities(topic_analysis, gap_analysis)
        
        # Prioritize opportunities
        high_priority = [opp for opp in opportunities if opp.priority == "high"]
        medium_priority = [opp for opp in opportunities if opp.priority == "medium"] 
        low_priority = [opp for opp in opportunities if opp.priority == "low"]
        
        # Generate content calendar suggestions
        calendar_suggestions = self._generate_content_calendar(high_priority, medium_priority)
        
        # Create strategic recommendations
        strategic_recs = self._generate_strategic_recommendations(topic_analysis, gap_analysis)
        
        # Identify topics for competitive monitoring
        monitoring_topics = self._identify_monitoring_topics(topic_analysis, gap_analysis)
        
        matrix = TopicOpportunityMatrix(
            high_priority_opportunities=sorted(high_priority, key=lambda x: x.opportunity_score, reverse=True),
            medium_priority_opportunities=sorted(medium_priority, key=lambda x: x.opportunity_score, reverse=True),
            low_priority_opportunities=sorted(low_priority, key=lambda x: x.opportunity_score, reverse=True),
            content_calendar_suggestions=calendar_suggestions,
            strategic_recommendations=strategic_recs,
            competitive_monitoring_topics=monitoring_topics
        )
        
        logger.info(f"Generated matrix with {len(high_priority)} high-priority opportunities")
        return matrix
        
    def _create_topic_opportunities(self, topic_analysis, gap_analysis) -> List[TopicOpportunity]:
        """Create topic opportunities from analysis results."""
        opportunities = []
        
        # Process high-opportunity gaps
        for gap in gap_analysis.high_opportunity_gaps:
            opportunity = TopicOpportunity(
                topic=gap.topic,
                priority="high",
                opportunity_score=gap.opportunity_score,
                competitive_landscape=self._describe_competitive_landscape(gap),
                recommended_approach=gap.suggested_approach,
                target_keywords=gap.supporting_keywords,
                estimated_difficulty=self._estimate_difficulty(gap),
                content_type_suggestions=self._suggest_content_types(gap.topic),
                hvacr_school_coverage=self._analyze_hvacr_school_coverage(gap.topic, topic_analysis),
                market_demand_indicators=self._get_market_demand_indicators(gap.topic, topic_analysis)
            )
            opportunities.append(opportunity)
            
        # Process medium-opportunity gaps  
        for gap in gap_analysis.medium_opportunity_gaps:
            opportunity = TopicOpportunity(
                topic=gap.topic,
                priority="medium",
                opportunity_score=gap.opportunity_score,
                competitive_landscape=self._describe_competitive_landscape(gap),
                recommended_approach=gap.suggested_approach,
                target_keywords=gap.supporting_keywords,
                estimated_difficulty=self._estimate_difficulty(gap),
                content_type_suggestions=self._suggest_content_types(gap.topic),
                hvacr_school_coverage=self._analyze_hvacr_school_coverage(gap.topic, topic_analysis),
                market_demand_indicators=self._get_market_demand_indicators(gap.topic, topic_analysis)
            )
            opportunities.append(opportunity)
            
        # Process select low-opportunity gaps (only highest scoring)
        top_low_gaps = sorted(gap_analysis.low_opportunity_gaps, key=lambda x: x.opportunity_score, reverse=True)[:10]
        for gap in top_low_gaps:
            opportunity = TopicOpportunity(
                topic=gap.topic,
                priority="low",
                opportunity_score=gap.opportunity_score,
                competitive_landscape=self._describe_competitive_landscape(gap),
                recommended_approach=gap.suggested_approach,
                target_keywords=gap.supporting_keywords,
                estimated_difficulty=self._estimate_difficulty(gap),
                content_type_suggestions=self._suggest_content_types(gap.topic),
                hvacr_school_coverage=self._analyze_hvacr_school_coverage(gap.topic, topic_analysis),
                market_demand_indicators=self._get_market_demand_indicators(gap.topic, topic_analysis)
            )
            opportunities.append(opportunity)
            
        return opportunities
        
    def _describe_competitive_landscape(self, gap) -> str:
        """Describe the competitive landscape for a topic."""
        comp_strength = gap.competitive_strength
        our_coverage = gap.our_coverage
        
        if comp_strength < 3:
            landscape = "Low competitive coverage - opportunity to lead"
        elif comp_strength < 6:
            landscape = "Moderate competitive coverage - differentiation possible"
        else:
            landscape = "High competitive coverage - requires unique positioning"
            
        if our_coverage < 2:
            landscape += " | Minimal current coverage"
        elif our_coverage < 5:
            landscape += " | Some current coverage" 
        else:
            landscape += " | Strong current coverage"
            
        return landscape
        
    def _estimate_difficulty(self, gap) -> str:
        """Estimate content creation difficulty."""
        # Simplified difficulty assessment
        if gap.competitive_strength > 7:
            return "challenging"
        elif gap.competitive_strength > 4:
            return "moderate"
        else:
            return "easy"
            
    def _suggest_content_types(self, topic: str) -> List[str]:
        """Suggest content types based on topic."""
        suggestions = []
        
        # Map topic to content types
        for category, content_types in self.content_type_map.items():
            if category in topic.lower():
                suggestions.extend(content_types)
                break
                
        # Default content types if no specific match
        if not suggestions:
            suggestions = ['Technical Guide', 'Best Practices', 'Industry Analysis', 'How-to Article']
            
        return list(set(suggestions))  # Remove duplicates
        
    def _analyze_hvacr_school_coverage(self, topic: str, topic_analysis) -> str:
        """Analyze how HVACRSchool covers this topic."""
        hvacr_topics = topic_analysis.hvacr_school_priority_topics
        
        if topic in hvacr_topics:
            score = hvacr_topics[topic]
            if score > 20:
                return "Heavy coverage - major focus area"
            elif score > 10:
                return "Moderate coverage - regular topic"
            else:
                return "Light coverage - occasional mention"
        else:
            return "No significant coverage identified"
            
    def _get_market_demand_indicators(self, topic: str, topic_analysis) -> Dict[str, any]:
        """Get market demand indicators for topic."""
        return {
            'primary_topic_score': topic_analysis.primary_topics.get(topic, 0),
            'secondary_topic_score': topic_analysis.secondary_topics.get(topic, 0),
            'technical_depth_score': topic_analysis.technical_depth_scores.get(topic, 0.0),
            'hvacr_priority': topic_analysis.hvacr_school_priority_topics.get(topic, 0)
        }
        
    def _generate_content_calendar(self, high_priority: List[TopicOpportunity], medium_priority: List[TopicOpportunity]) -> List[Dict[str, str]]:
        """Generate content calendar suggestions."""
        calendar = []
        
        # Quarterly planning for high-priority topics
        quarters = ["Q1", "Q2", "Q3", "Q4"]
        high_topics = high_priority[:12]  # Top 12 for quarterly planning
        
        for i, topic in enumerate(high_topics):
            quarter = quarters[i % 4]
            calendar.append({
                'quarter': quarter,
                'topic': topic.topic,
                'priority': 'high',
                'suggested_content_type': topic.content_type_suggestions[0] if topic.content_type_suggestions else 'Technical Guide',
                'rationale': f"Opportunity score: {topic.opportunity_score:.1f}"
            })
            
        # Monthly suggestions for medium-priority topics
        medium_topics = medium_priority[:12] 
        months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
        
        for i, topic in enumerate(medium_topics):
            calendar.append({
                'month': months[i % 12],
                'topic': topic.topic,
                'priority': 'medium',
                'suggested_content_type': topic.content_type_suggestions[0] if topic.content_type_suggestions else 'Best Practices',
                'rationale': f"Opportunity score: {topic.opportunity_score:.1f}"
            })
            
        return calendar
        
    def _generate_strategic_recommendations(self, topic_analysis, gap_analysis) -> List[str]:
        """Generate strategic content recommendations."""
        recommendations = []
        
        # Analyze overall landscape
        high_gaps = len(gap_analysis.high_opportunity_gaps)
        strengths = len(gap_analysis.content_strengths)
        threats = len(gap_analysis.competitive_threats)
        
        if high_gaps > 10:
            recommendations.append("High number of content opportunities identified - consider ramping up content production")
            
        if threats > strengths:
            recommendations.append("Competitive threats exceed current strengths - focus on defensive content strategy")
        else:
            recommendations.append("Strong competitive position - opportunity for thought leadership content")
            
        # Topic-specific recommendations
        top_hvacr_topics = sorted(topic_analysis.hvacr_school_priority_topics.items(), key=lambda x: x[1], reverse=True)[:5]
        if top_hvacr_topics:
            top_topic = top_hvacr_topics[0][0]
            recommendations.append(f"HVACRSchool heavily focuses on '{top_topic}' - consider advanced/unique angle")
            
        # Technical depth recommendations
        high_depth_topics = [topic for topic, score in topic_analysis.technical_depth_scores.items() if score > 0.8]
        if high_depth_topics:
            recommendations.append(f"Focus on technically complex topics: {', '.join(high_depth_topics[:3])}")
            
        return recommendations
        
    def _identify_monitoring_topics(self, topic_analysis, gap_analysis) -> List[str]:
        """Identify topics that should be monitored for competitive changes."""
        monitoring = []
        
        # Monitor topics where we're weak and competitors are strong
        for gap in gap_analysis.high_opportunity_gaps:
            if gap.competitive_strength > 6 and gap.our_coverage < 4:
                monitoring.append(gap.topic)
                
        # Monitor top HVACRSchool topics
        top_hvacr = sorted(topic_analysis.hvacr_school_priority_topics.items(), key=lambda x: x[1], reverse=True)[:5]
        monitoring.extend([topic for topic, _ in top_hvacr])
        
        return list(set(monitoring))  # Remove duplicates
        
    def export_matrix(self, matrix: TopicOpportunityMatrix, output_path: Path):
        """Export topic opportunity matrix to JSON and markdown."""
        
        # JSON export for data processing
        json_data = {
            'high_priority_opportunities': [asdict(opp) for opp in matrix.high_priority_opportunities],
            'medium_priority_opportunities': [asdict(opp) for opp in matrix.medium_priority_opportunities],
            'low_priority_opportunities': [asdict(opp) for opp in matrix.low_priority_opportunities],
            'content_calendar_suggestions': matrix.content_calendar_suggestions,
            'strategic_recommendations': matrix.strategic_recommendations,
            'competitive_monitoring_topics': matrix.competitive_monitoring_topics,
            'generated_at': datetime.now().isoformat()
        }
        
        json_path = output_path.with_suffix('.json')
        json_path.write_text(json.dumps(json_data, indent=2))
        
        # Markdown export for human readability
        md_content = self._generate_markdown_report(matrix)
        md_path = output_path.with_suffix('.md')
        md_path.write_text(md_content)
        
        logger.info(f"Topic opportunity matrix exported to {json_path} and {md_path}")
        
    def _generate_markdown_report(self, matrix: TopicOpportunityMatrix) -> str:
        """Generate markdown report from topic opportunity matrix."""
        
        md = f"""# HVAC Blog Topic Opportunity Matrix
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

## Executive Summary
- **High Priority Opportunities**: {len(matrix.high_priority_opportunities)}
- **Medium Priority Opportunities**: {len(matrix.medium_priority_opportunities)}  
- **Low Priority Opportunities**: {len(matrix.low_priority_opportunities)}

## High Priority Topic Opportunities

"""
        
        for i, opp in enumerate(matrix.high_priority_opportunities[:10], 1):
            md += f"""### {i}. {opp.topic.replace('_', ' ').title()}
- **Opportunity Score**: {opp.opportunity_score:.1f}
- **Competitive Landscape**: {opp.competitive_landscape}
- **Recommended Approach**: {opp.recommended_approach}
- **Content Types**: {', '.join(opp.content_type_suggestions)}
- **Difficulty**: {opp.estimated_difficulty}
- **Target Keywords**: {', '.join(opp.target_keywords[:5])}

"""
        
        md += "\n## Strategic Recommendations\n\n"
        for i, rec in enumerate(matrix.strategic_recommendations, 1):
            md += f"{i}. {rec}\n"
            
        md += "\n## Content Calendar Suggestions\n\n"
        md += "| Period | Topic | Priority | Content Type | Rationale |\n"
        md += "|--------|-------|----------|--------------|----------|\n"
        
        for suggestion in matrix.content_calendar_suggestions[:20]:
            period = suggestion.get('quarter', suggestion.get('month', 'TBD'))
            md += f"| {period} | {suggestion['topic']} | {suggestion['priority']} | {suggestion['suggested_content_type']} | {suggestion['rationale']} |\n"
            
        return md