#!/usr/bin/env python3
"""
Content Analysis Orchestrator

Orchestrates daily content analysis for HKIA content, generating
intelligence reports with Claude Haiku analysis, engagement metrics,
and keyword insights.
"""

import os
import sys
import logging
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any, Optional

# Add src to path for imports
if str(Path(__file__).parent.parent.parent) not in sys.path:
    sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from src.content_analysis.intelligence_aggregator import IntelligenceAggregator


class ContentAnalysisOrchestrator:
    """Orchestrates daily content analysis and intelligence generation"""
    
    def __init__(self, data_dir: Optional[Path] = None, logs_dir: Optional[Path] = None):
        """Initialize the content analysis orchestrator"""
        
        # Use relative paths by default, absolute for production
        default_data = Path("data") if Path("data").exists() else Path("/opt/hvac-kia-content/data")
        default_logs = Path("logs") if Path("logs").exists() else Path("/opt/hvac-kia-content/logs")
        
        self.data_dir = data_dir or default_data
        self.logs_dir = logs_dir or default_logs
        
        # Ensure directories exist
        self.data_dir.mkdir(parents=True, exist_ok=True)
        self.logs_dir.mkdir(parents=True, exist_ok=True)
        
        # Setup logging
        self.logger = self._setup_logger()
        
        # Initialize intelligence aggregator
        self.intelligence_aggregator = IntelligenceAggregator(self.data_dir)
        
        self.logger.info("Content Analysis Orchestrator initialized")
        self.logger.info(f"Data directory: {self.data_dir}")
        self.logger.info(f"Intelligence directory: {self.data_dir / 'intelligence'}")

    def run_daily_analysis(self, date: Optional[datetime] = None) -> Dict[str, Any]:
        """Run daily content analysis and generate intelligence report"""
        
        if date is None:
            date = datetime.now()
        
        date_str = date.strftime('%Y-%m-%d')
        
        self.logger.info(f"Starting daily content analysis for {date_str}")
        
        try:
            # Generate daily intelligence report
            intelligence_report = self.intelligence_aggregator.generate_daily_intelligence(date)
            
            # Log summary
            meta = intelligence_report.get('meta', {})
            hkia_analysis = intelligence_report.get('hkia_analysis', {})
            
            self.logger.info(f"Daily analysis complete for {date_str}:")
            self.logger.info(f"  - HKIA items processed: {meta.get('total_hkia_items', 0)}")
            self.logger.info(f"  - Content classified: {hkia_analysis.get('content_classified', 0)}")
            self.logger.info(f"  - Trending keywords: {len(hkia_analysis.get('trending_keywords', []))}")
            
            # Print key insights
            strategic_insights = intelligence_report.get('strategic_insights', {})
            opportunities = strategic_insights.get('content_opportunities', [])
            if opportunities:
                self.logger.info(f"  - Top opportunity: {opportunities[0]}")
            
            return intelligence_report
            
        except Exception as e:
            self.logger.error(f"Error in daily content analysis for {date_str}: {e}")
            raise

    def run_weekly_analysis(self, end_date: Optional[datetime] = None) -> Dict[str, Any]:
        """Run weekly content analysis and generate summary report"""
        
        if end_date is None:
            end_date = datetime.now()
        
        week_str = end_date.strftime('%Y-%m-%d')
        
        self.logger.info(f"Starting weekly content analysis for week ending {week_str}")
        
        try:
            # Generate weekly intelligence report
            weekly_report = self.intelligence_aggregator.generate_weekly_intelligence(end_date)
            
            self.logger.info(f"Weekly analysis complete for {week_str}")
            
            return weekly_report
            
        except Exception as e:
            self.logger.error(f"Error in weekly content analysis for {week_str}: {e}")
            raise

    def get_latest_intelligence(self) -> Optional[Dict[str, Any]]:
        """Get the latest daily intelligence report"""
        
        intelligence_dir = self.data_dir / "intelligence" / "daily"
        
        if not intelligence_dir.exists():
            return None
        
        # Find latest intelligence file
        intelligence_files = list(intelligence_dir.glob("hkia_intelligence_*.json"))
        
        if not intelligence_files:
            return None
        
        # Sort by date and get latest
        latest_file = sorted(intelligence_files)[-1]
        
        try:
            import json
            with open(latest_file, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            self.logger.error(f"Error reading latest intelligence file {latest_file}: {e}")
            return None

    def print_intelligence_summary(self, intelligence: Optional[Dict[str, Any]] = None) -> None:
        """Print a summary of intelligence report to console"""
        
        if intelligence is None:
            intelligence = self.get_latest_intelligence()
        
        if not intelligence:
            print("❌ No intelligence data available")
            return
        
        print("\n📊 HKIA Content Intelligence Summary")
        print("=" * 50)
        
        # Report metadata
        report_date = intelligence.get('report_date', 'Unknown')
        print(f"📅 Report Date: {report_date}")
        
        meta = intelligence.get('meta', {})
        print(f"📄 Total Items Processed: {meta.get('total_hkia_items', 0)}")
        print(f"🤖 Analysis Version: {meta.get('analysis_version', 'Unknown')}")
        
        # HKIA Analysis Summary
        hkia_analysis = intelligence.get('hkia_analysis', {})
        
        print(f"\n🧠 Content Classification:")
        print(f"   Items Classified: {hkia_analysis.get('content_classified', 0)}")
        
        # Topic distribution
        topic_dist = hkia_analysis.get('topic_distribution', {})
        if topic_dist:
            print(f"\n📋 Top Topics:")
            sorted_topics = sorted(topic_dist.items(), key=lambda x: x[1].get('count', 0), reverse=True)
            for topic, data in sorted_topics[:5]:
                count = data.get('count', 0)
                sentiment = data.get('avg_sentiment', 0)
                print(f"   • {topic.replace('_', ' ').title()}: {count} items (sentiment: {sentiment:.2f})")
        
        # Engagement summary
        engagement_summary = hkia_analysis.get('engagement_summary', {})
        if engagement_summary:
            print(f"\n📈 Engagement Summary:")
            for source, metrics in engagement_summary.items():
                if isinstance(metrics, dict) and 'avg_engagement_rate' in metrics:
                    rate = metrics.get('avg_engagement_rate', 0)
                    trending = metrics.get('trending_count', 0)
                    print(f"   • {source.title()}: {rate:.4f} avg rate, {trending} trending")
        
        # Trending keywords
        trending_kw = hkia_analysis.get('trending_keywords', [])
        if trending_kw:
            print(f"\n🔥 Trending Keywords:")
            for kw_data in trending_kw[:5]:
                keyword = kw_data.get('keyword', 'Unknown')
                frequency = kw_data.get('frequency', 0)
                print(f"   • {keyword}: {frequency} mentions")
        
        # Strategic insights
        insights = intelligence.get('strategic_insights', {})
        opportunities = insights.get('content_opportunities', [])
        if opportunities:
            print(f"\n💡 Content Opportunities:")
            for opp in opportunities[:3]:
                print(f"   • {opp}")
        
        improvements = insights.get('areas_for_improvement', [])
        if improvements:
            print(f"\n🎯 Areas for Improvement:")
            for imp in improvements[:3]:
                print(f"   • {imp}")
        
        print("\n" + "=" * 50)

    def _setup_logger(self) -> logging.Logger:
        """Setup logger for content analysis orchestrator"""
        
        logger = logging.getLogger('content_analysis_orchestrator')
        logger.setLevel(logging.INFO)
        
        # Clear existing handlers
        logger.handlers.clear()
        
        # Console handler
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        
        # File handler
        log_dir = self.logs_dir / "content_analysis"
        log_dir.mkdir(exist_ok=True)
        
        log_file = log_dir / "content_analysis.log"
        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(logging.DEBUG)
        
        # Formatter
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        console_handler.setFormatter(formatter)
        file_handler.setFormatter(formatter)
        
        logger.addHandler(console_handler)
        logger.addHandler(file_handler)
        
        return logger


def main():
    """Main function for running content analysis"""
    
    import argparse
    
    parser = argparse.ArgumentParser(description='HKIA Content Analysis Orchestrator')
    parser.add_argument('--mode', choices=['daily', 'weekly', 'summary'], default='daily',
                       help='Analysis mode to run')
    parser.add_argument('--date', type=str, help='Date for analysis (YYYY-MM-DD)')
    parser.add_argument('--data-dir', type=str, help='Data directory path')
    parser.add_argument('--logs-dir', type=str, help='Logs directory path')
    
    args = parser.parse_args()
    
    # Parse date if provided
    date = None
    if args.date:
        try:
            date = datetime.strptime(args.date, '%Y-%m-%d')
        except ValueError:
            print(f"❌ Invalid date format: {args.date}. Use YYYY-MM-DD")
            sys.exit(1)
    
    # Initialize orchestrator
    try:
        data_dir = Path(args.data_dir) if args.data_dir else None
        logs_dir = Path(args.logs_dir) if args.logs_dir else None
        
        orchestrator = ContentAnalysisOrchestrator(data_dir, logs_dir)
        
        # Run analysis based on mode
        if args.mode == 'daily':
            print(f"🚀 Running daily content analysis...")
            intelligence = orchestrator.run_daily_analysis(date)
            orchestrator.print_intelligence_summary(intelligence)
            
        elif args.mode == 'weekly':
            print(f"📊 Running weekly content analysis...")
            weekly_report = orchestrator.run_weekly_analysis(date)
            print(f"✅ Weekly analysis complete")
            
        elif args.mode == 'summary':
            print(f"📋 Displaying latest intelligence summary...")
            orchestrator.print_intelligence_summary()
        
    except Exception as e:
        print(f"❌ Error running content analysis: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()