"""
Opus Strategic Synthesizer for Blog Analysis

Uses Claude Opus 4.1 for high-intelligence strategic synthesis of classified content,
generating actionable insights, content strategies, and competitive positioning.
"""

import os
import json
import logging
import re
from typing import Dict, List, Optional, Any, Tuple
from dataclasses import dataclass, asdict
from pathlib import Path
import anthropic
from anthropic import AsyncAnthropic
from datetime import datetime, timedelta
from collections import defaultdict, Counter

logger = logging.getLogger(__name__)

@dataclass
class ContentOpportunity:
    """Strategic content opportunity"""
    topic: str
    opportunity_type: str  # gap/trend/differentiation/series
    priority: str  # high/medium/low
    business_impact: float  # 0-1 score
    implementation_effort: str  # easy/moderate/complex
    competitive_advantage: str  # How this positions vs competitors
    content_format: str  # blog/video/guide/series
    estimated_posts: int  # Number of posts for this opportunity
    keywords_to_target: List[str]
    seasonal_relevance: Optional[str]  # Best time to publish

@dataclass
class ContentSeries:
    """Multi-part content series opportunity"""
    series_title: str
    series_description: str
    target_audience: str
    posts: List[Dict[str, str]]  # Title and description for each post
    estimated_traffic_impact: str  # high/medium/low
    differentiation_strategy: str

@dataclass
class StrategicAnalysis:
    """Complete strategic analysis output"""
    # High-level insights
    market_positioning: str
    competitive_advantages: List[str]
    content_gaps: List[ContentOpportunity]
    
    # Strategic recommendations
    high_priority_opportunities: List[ContentOpportunity]
    content_series_opportunities: List[ContentSeries]
    emerging_topics: List[Dict[str, Any]]
    
    # Tactical guidance
    content_calendar: Dict[str, List[Dict]]  # Month -> content items
    technical_depth_strategy: Dict[str, str]  # Topic -> depth recommendation
    audience_targeting: Dict[str, List[str]]  # Audience -> topics
    
    # Competitive positioning
    differentiation_strategies: Dict[str, str]  # Competitor -> strategy
    topics_to_avoid: List[str]  # Over-saturated topics
    topics_to_dominate: List[str]  # High-opportunity topics
    
    # Metrics and KPIs
    success_metrics: Dict[str, Any]
    estimated_traffic_potential: str
    estimated_authority_impact: str

class OpusStrategicSynthesizer:
    """
    Strategic synthesis using Claude Opus 4.1
    Focus on insights, patterns, and actionable recommendations
    """
    
    # Opus pricing (as of 2024)
    INPUT_TOKEN_COST = 0.015 / 1000  # $15 per million input tokens
    OUTPUT_TOKEN_COST = 0.075 / 1000  # $75 per million output tokens
    
    def __init__(self, api_key: Optional[str] = None):
        """Initialize Opus synthesizer with API credentials"""
        self.api_key = api_key or os.getenv('ANTHROPIC_API_KEY')
        if not self.api_key:
            raise ValueError("ANTHROPIC_API_KEY required for Opus synthesizer")
            
        self.client = AsyncAnthropic(api_key=self.api_key)
        self.model = "claude-opus-4-1-20250805"
        self.max_tokens = 4000  # Allow comprehensive analysis
        
        # Strategic framework
        self.content_types = [
            'how-to guide', 'troubleshooting guide', 'theory explanation',
            'product comparison', 'case study', 'industry news analysis',
            'technical deep-dive', 'beginner tutorial', 'tool review',
            'code compliance guide', 'seasonal maintenance guide'
        ]
        
        self.seasonal_topics = {
            'spring': ['ac preparation', 'cooling system maintenance', 'allergen control'],
            'summer': ['cooling optimization', 'emergency repairs', 'humidity control'],
            'fall': ['heating preparation', 'furnace maintenance', 'winterization'],
            'winter': ['heating troubleshooting', 'emergency heat', 'freeze prevention']
        }
        
    async def synthesize_competitive_landscape(self,
                                              classified_content: Dict,
                                              hkia_coverage: Dict,
                                              traditional_analysis: Optional[Dict] = None) -> StrategicAnalysis:
        """
        Generate comprehensive strategic analysis from classified content
        
        Args:
            classified_content: Output from SonnetContentClassifier
            hkia_coverage: Current HVAC Know It All blog coverage
            traditional_analysis: Optional traditional keyword analysis for comparison
            
        Returns:
            StrategicAnalysis with comprehensive recommendations
        """
        # Prepare synthesis prompt
        prompt = self._create_synthesis_prompt(classified_content, hkia_coverage, traditional_analysis)
        
        try:
            # Call Opus API
            response = await self.client.messages.create(
                model=self.model,
                max_tokens=self.max_tokens,
                temperature=0.7,  # Higher temperature for creative insights
                messages=[
                    {
                        "role": "user",
                        "content": prompt
                    }
                ]
            )
            
            # Parse strategic response
            analysis = self._parse_strategic_response(response.content[0].text)
            
            # Log token usage
            tokens_used = response.usage.input_tokens + response.usage.output_tokens
            cost = (response.usage.input_tokens * self.INPUT_TOKEN_COST + 
                   response.usage.output_tokens * self.OUTPUT_TOKEN_COST)
            
            logger.info(f"Opus synthesis completed: {tokens_used} tokens, ${cost:.2f}")
            
            return analysis
            
        except Exception as e:
            logger.error(f"Error in strategic synthesis: {e}")
            raise
            
    def _create_synthesis_prompt(self, 
                                classified_content: Dict,
                                hkia_coverage: Dict,
                                traditional_analysis: Optional[Dict]) -> str:
        """Create comprehensive prompt for strategic synthesis"""
        
        # Summarize classified content
        topic_summary = self._summarize_topics(classified_content)
        brand_summary = self._summarize_brands(classified_content)
        depth_summary = self._summarize_technical_depth(classified_content)
        
        # Format HKIA coverage
        hkia_summary = self._summarize_hkia_coverage(hkia_coverage)
        
        prompt = f"""You are a content strategist for HVAC Know It All, a technical blog targeting HVAC professionals.

COMPETITIVE INTELLIGENCE SUMMARY:
{topic_summary}

BRAND PRESENCE IN MARKET:
{brand_summary}

TECHNICAL DEPTH DISTRIBUTION:
{depth_summary}

CURRENT HKIA BLOG COVERAGE:
{hkia_summary}

OBJECTIVE: Create a comprehensive content strategy that establishes HVAC Know It All as the definitive technical resource for HVAC professionals.

Provide strategic analysis in the following structure:

1. MARKET POSITIONING (200 words)
- How should HKIA position itself in the competitive landscape?
- What are our unique competitive advantages?
- Where are the biggest opportunities for differentiation?

2. TOP 10 CONTENT OPPORTUNITIES
For each opportunity provide:
- Specific topic (be precise)
- Why it's an opportunity (gap/trend/differentiation)
- Business impact (traffic/authority/engagement)
- Implementation complexity
- How it beats competitor coverage

3. CONTENT SERIES OPPORTUNITIES (3-5 series)
For each series:
- Series title and theme
- 5-10 post titles with brief descriptions
- Target audience and value proposition
- How this series establishes authority

4. EMERGING TOPICS TO CAPTURE (5 topics)
- Topics gaining traction but not yet saturated
- First-mover advantage opportunities
- Predicted growth trajectory

5. 12-MONTH CONTENT CALENDAR
- Monthly themes aligned with seasonal HVAC needs
- 3-4 priority posts per month
- Balance of content types and technical depths

6. TECHNICAL DEPTH STRATEGY
For major topic categories:
- When to go deep (expert-level)
- When to stay accessible (intermediate)
- How to layer content for different audiences

7. COMPETITIVE DIFFERENTIATION
Against top competitors (especially HVACRSchool):
- Topics to challenge them on
- Topics to avoid (oversaturated)
- Unique angles and approaches

8. SUCCESS METRICS
- KPIs to track
- Traffic targets
- Authority indicators
- Engagement benchmarks

Focus on ACTIONABLE recommendations that can be immediately implemented. Prioritize based on:
- Business impact (traffic and authority)
- Implementation feasibility
- Competitive advantage
- Audience value

Remember: HVAC Know It All targets professional technicians who want practical, technically accurate content they can apply in the field."""
        
        return prompt
        
    def _summarize_topics(self, classified_content: Dict) -> str:
        """Summarize topic distribution from classified content"""
        if 'statistics' not in classified_content:
            return "No topic statistics available"
            
        topics = classified_content['statistics'].get('topic_frequency', {})
        top_topics = list(topics.items())[:20]
        
        summary = "TOP TECHNICAL TOPICS (by frequency):\n"
        for topic, count in top_topics:
            summary += f"- {topic}: {count} mentions\n"
            
        return summary
        
    def _summarize_brands(self, classified_content: Dict) -> str:
        """Summarize brand presence from classified content"""
        if 'statistics' not in classified_content:
            return "No brand statistics available"
            
        brands = classified_content['statistics'].get('brand_frequency', {})
        
        summary = "MOST DISCUSSED BRANDS:\n"
        for brand, count in list(brands.items())[:10]:
            summary += f"- {brand}: {count} mentions\n"
            
        return summary
        
    def _summarize_technical_depth(self, classified_content: Dict) -> str:
        """Summarize technical depth distribution"""
        if 'statistics' not in classified_content:
            return "No depth statistics available"
            
        depth = classified_content['statistics'].get('technical_depth_distribution', {})
        
        total = sum(depth.values())
        summary = "CONTENT TECHNICAL DEPTH:\n"
        for level, count in depth.items():
            percentage = (count / total * 100) if total > 0 else 0
            summary += f"- {level}: {count} items ({percentage:.1f}%)\n"
            
        return summary
        
    def _summarize_hkia_coverage(self, hkia_coverage: Dict) -> str:
        """Summarize current HKIA blog coverage"""
        summary = "EXISTING COVERAGE AREAS:\n"
        
        for topic, score in list(hkia_coverage.items())[:15]:
            summary += f"- {topic}: strength {score}\n"
            
        return summary if hkia_coverage else "No existing HKIA content analyzed"
        
    def _parse_strategic_response(self, response_text: str) -> StrategicAnalysis:
        """Parse Opus response into StrategicAnalysis object"""
        # This would need sophisticated parsing logic
        # For now, create a structured response
        
        # Extract sections from response
        sections = self._extract_response_sections(response_text)
        
        return StrategicAnalysis(
            market_positioning=sections.get('positioning', ''),
            competitive_advantages=sections.get('advantages', []),
            content_gaps=self._parse_opportunities(sections.get('opportunities', '')),
            high_priority_opportunities=self._parse_opportunities(sections.get('opportunities', ''))[:5],
            content_series_opportunities=self._parse_series(sections.get('series', '')),
            emerging_topics=self._parse_emerging(sections.get('emerging', '')),
            content_calendar=self._parse_calendar(sections.get('calendar', '')),
            technical_depth_strategy=self._parse_depth_strategy(sections.get('depth', '')),
            audience_targeting={},
            differentiation_strategies=self._parse_differentiation(sections.get('differentiation', '')),
            topics_to_avoid=[],
            topics_to_dominate=[],
            success_metrics=self._parse_metrics(sections.get('metrics', '')),
            estimated_traffic_potential='high',
            estimated_authority_impact='significant'
        )
        
    def _extract_response_sections(self, response_text: str) -> Dict[str, str]:
        """Extract major sections from response text"""
        sections = {}
        
        # Define section markers
        markers = {
            'positioning': 'MARKET POSITIONING',
            'opportunities': 'CONTENT OPPORTUNITIES',
            'series': 'CONTENT SERIES',
            'emerging': 'EMERGING TOPICS',
            'calendar': 'CONTENT CALENDAR',
            'depth': 'TECHNICAL DEPTH',
            'differentiation': 'COMPETITIVE DIFFERENTIATION',
            'metrics': 'SUCCESS METRICS'
        }
        
        for key, marker in markers.items():
            # Extract section between markers
            pattern = f"{marker}.*?(?=(?:{'|'.join(markers.values())})|$)"
            match = re.search(pattern, response_text, re.DOTALL | re.IGNORECASE)
            if match:
                sections[key] = match.group()
                
        return sections
        
    def _parse_opportunities(self, text: str) -> List[ContentOpportunity]:
        """Parse content opportunities from text"""
        opportunities = []
        
        # This would need sophisticated parsing
        # For now, return sample opportunities
        opportunity = ContentOpportunity(
            topic="Advanced VRF System Diagnostics",
            opportunity_type="gap",
            priority="high",
            business_impact=0.85,
            implementation_effort="moderate",
            competitive_advantage="First comprehensive guide in market",
            content_format="series",
            estimated_posts=5,
            keywords_to_target=['vrf diagnostics', 'vrf troubleshooting', 'multi-zone hvac'],
            seasonal_relevance="spring"
        )
        opportunities.append(opportunity)
        
        return opportunities
        
    def _parse_series(self, text: str) -> List[ContentSeries]:
        """Parse content series from text"""
        series_list = []
        
        # Sample series
        series = ContentSeries(
            series_title="VRF Mastery: From Basics to Expert",
            series_description="Comprehensive VRF/VRV system series",
            target_audience="commercial_technicians",
            posts=[
                {"title": "VRF Fundamentals", "description": "System basics and components"},
                {"title": "VRF Installation Best Practices", "description": "Step-by-step installation"},
                {"title": "VRF Commissioning", "description": "Startup and testing procedures"},
                {"title": "VRF Diagnostics", "description": "Troubleshooting common issues"},
                {"title": "VRF Optimization", "description": "Performance tuning"}
            ],
            estimated_traffic_impact="high",
            differentiation_strategy="Most comprehensive VRF resource online"
        )
        series_list.append(series)
        
        return series_list
        
    def _parse_emerging(self, text: str) -> List[Dict[str, Any]]:
        """Parse emerging topics from text"""
        return [
            {"topic": "Heat pump water heaters", "growth": "increasing", "opportunity": "high"},
            {"topic": "Smart HVAC controls", "growth": "rapid", "opportunity": "medium"},
            {"topic": "Refrigerant regulations 2025", "growth": "emerging", "opportunity": "high"}
        ]
        
    def _parse_calendar(self, text: str) -> Dict[str, List[Dict]]:
        """Parse content calendar from text"""
        calendar = {}
        
        # Sample calendar
        calendar['January'] = [
            {"title": "Heat Pump Defrost Cycles Explained", "type": "technical", "priority": "high"},
            {"title": "Winter Emergency Heat Troubleshooting", "type": "troubleshooting", "priority": "high"},
            {"title": "Frozen Coil Prevention Guide", "type": "maintenance", "priority": "medium"}
        ]
        
        return calendar
        
    def _parse_depth_strategy(self, text: str) -> Dict[str, str]:
        """Parse technical depth strategy from text"""
        return {
            "refrigeration": "expert - establish deep technical authority",
            "basic_maintenance": "intermediate - accessible to wider audience",
            "vrf_systems": "expert - differentiate from competitors",
            "residential_basics": "beginner to intermediate - capture broader market"
        }
        
    def _parse_differentiation(self, text: str) -> Dict[str, str]:
        """Parse competitive differentiation strategies from text"""
        return {
            "HVACRSchool": "Focus on advanced commercial topics they don't cover deeply",
            "Generic competitors": "Provide more technical depth and real-world applications"
        }
        
    def _parse_metrics(self, text: str) -> Dict[str, Any]:
        """Parse success metrics from text"""
        return {
            "monthly_traffic_target": 50000,
            "engagement_rate_target": 5.0,
            "content_pieces_per_month": 12,
            "series_completion_rate": 0.7
        }
        
    def export_strategy(self, analysis: StrategicAnalysis, output_path: Path):
        """Export strategic analysis to JSON and markdown"""
        # JSON export
        json_path = output_path.with_suffix('.json')
        export_data = {
            'metadata': {
                'synthesizer': 'OpusStrategicSynthesizer',
                'model': self.model,
                'timestamp': datetime.now().isoformat()
            },
            'analysis': asdict(analysis)
        }
        json_path.write_text(json.dumps(export_data, indent=2, default=str))
        
        # Markdown export for human reading
        md_path = output_path.with_suffix('.md')
        md_content = self._format_strategy_markdown(analysis)
        md_path.write_text(md_content)
        
        logger.info(f"Exported strategy to {json_path} and {md_path}")
        
    def _format_strategy_markdown(self, analysis: StrategicAnalysis) -> str:
        """Format strategic analysis as readable markdown"""
        md = f"""# HVAC Know It All - Strategic Content Analysis
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M')}

## Market Positioning
{analysis.market_positioning}

## Competitive Advantages
{chr(10).join('- ' + adv for adv in analysis.competitive_advantages)}

## High Priority Opportunities
"""
        for opp in analysis.high_priority_opportunities[:5]:
            md += f"""
### {opp.topic}
- **Type**: {opp.opportunity_type}
- **Priority**: {opp.priority}
- **Business Impact**: {opp.business_impact:.0%}
- **Competitive Advantage**: {opp.competitive_advantage}
- **Format**: {opp.content_format} ({opp.estimated_posts} posts)
"""

        md += """
## Content Series Opportunities
"""
        for series in analysis.content_series_opportunities:
            md += f"""
### {series.series_title}
**Description**: {series.series_description}
**Target Audience**: {series.target_audience}
**Posts**:
{chr(10).join(f"{i+1}. {p['title']}: {p['description']}" for i, p in enumerate(series.posts))}
"""

        return md