#!/usr/bin/env python3
"""
View LLM Analysis Results from S3
This script retrieves and displays LLM analysis results stored in S3
"""

import os
import sys
import json
import logging
from datetime import datetime
from typing import List, Dict, Any

# Add the project root to the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# Set up logging
logging.basicConfig(
    level=logging.INFO, 
    format='%(asctime)s [%(name)s] %(levelname)s: %(message)s'
)

def list_llm_analysis_results(bucket_name: str = None, limit: int = 10) -> List[Dict[str, Any]]:
    """List all LLM analysis results from S3"""
    try:
        from storage.config import load_config_from_env
        from storage.s3_adapter import S3Storage
        
        cfg = load_config_from_env()
        s3 = S3Storage(cfg, no_aws=False)
        
        bucket = bucket_name or cfg.s3_bucket_processed
        print(f"🔍 Listing LLM analysis results from bucket: {bucket}")
        
        # List analysis results
        analysis_results = []
        
        # Check different analysis folders
        analysis_folders = [
            'llm-analysis/',
            'scheduled-llm-analysis/',
            'threat-intelligence/'
        ]
        
        for folder in analysis_folders:
            objects = s3.list_objects(bucket, folder)
            json_files = [obj for obj in objects if obj.endswith('.json')]
            
            for obj_key in json_files:
                try:
                    json_content = s3.get_json(bucket, obj_key)
                    if json_content:
                        # Add metadata
                        json_content['_source_file'] = obj_key
                        json_content['_bucket'] = bucket
                        analysis_results.append(json_content)
                except Exception as e:
                    print(f"⚠️  Failed to load {obj_key}: {e}")
                    continue
        
        # Sort by upload date (most recent first)
        analysis_results.sort(key=lambda x: x.get('uploaded_at', ''), reverse=True)
        
        if limit:
            analysis_results = analysis_results[:limit]
        
        print(f"📊 Found {len(analysis_results)} LLM analysis results")
        return analysis_results
        
    except Exception as e:
        print(f"❌ Error listing LLM analysis results: {e}")
        return []

def display_analysis_summary(analysis: Dict[str, Any]) -> None:
    """Display a summary of an LLM analysis result"""
    print("\n" + "="*80)
    
    # Basic info
    source_file = analysis.get('_source_file', 'Unknown')
    uploaded_at = analysis.get('uploaded_at', 'Unknown')
    workflow_run_id = analysis.get('workflow_run_id', 'Unknown')
    
    print(f"📄 Analysis Result: {source_file}")
    print(f"📅 Uploaded: {uploaded_at}")
    print(f"🔄 Workflow Run: {workflow_run_id}")
    
    # Summary information
    if 'summary' in analysis:
        summary = analysis['summary']
        print(f"\n📊 Analysis Summary:")
        print(f"  Files retrieved: {summary.get('total_files_retrieved', 0)}")
        print(f"  Batches processed: {summary.get('batches_processed', 0)}")
        print(f"  Successful batches: {summary.get('successful_llm_batches', 0)}")
        print(f"  Documents analyzed: {summary.get('total_documents_analyzed', 0)}")
    
    # Pipeline metadata
    if 'pipeline_metadata' in analysis:
        metadata = analysis['pipeline_metadata']
        print(f"\n🔧 Configuration:")
        print(f"  LLM Provider: {metadata.get('llm_provider', 'Unknown')}")
        print(f"  Max Files: {metadata.get('limit', 'Unknown')}")
        print(f"  Batch Size: {metadata.get('batch_size', 'Unknown')}")
        print(f"  Created: {metadata.get('created_at', 'Unknown')}")
    
    # Threat intelligence findings
    if 'threat_findings' in analysis:
        findings = analysis['threat_findings']
        print(f"\n🎯 Threat Intelligence Findings: {len(findings)}")
        
        if findings:
            # Aggregate findings
            all_families = []
            all_techniques = []
            all_industries = []
            
            for finding in findings:
                all_families.extend(finding.get('ransomware_families', []))
                all_techniques.extend(finding.get('attack_techniques', []))
                all_industries.extend(finding.get('target_industries', []))
            
            if all_families:
                unique_families = list(set(all_families))
                print(f"  Ransomware Families: {', '.join(unique_families[:5])}")
                if len(unique_families) > 5:
                    print(f"    ... and {len(unique_families) - 5} more")
            
            if all_techniques:
                unique_techniques = list(set(all_techniques))
                print(f"  Attack Techniques: {', '.join(unique_techniques[:5])}")
                if len(unique_techniques) > 5:
                    print(f"    ... and {len(unique_techniques) - 5} more")
            
            if all_industries:
                unique_industries = list(set(all_industries))
                print(f"  Target Industries: {', '.join(unique_industries[:5])}")
                if len(unique_industries) > 5:
                    print(f"    ... and {len(unique_industries) - 5} more")

def display_detailed_findings(analysis: Dict[str, Any]) -> None:
    """Display detailed threat intelligence findings"""
    if 'threat_findings' not in analysis:
        return
    
    findings = analysis['threat_findings']
    if not findings:
        return
    
    print(f"\n🔍 Detailed Threat Intelligence Findings:")
    print("-" * 60)
    
    for i, finding in enumerate(findings, 1):
        print(f"\nFinding {i}:")
        print(f"  Batch ID: {finding.get('batch_id', 'Unknown')}")
        print(f"  Confidence: {finding.get('confidence_level', 'Unknown')}/10")
        
        families = finding.get('ransomware_families', [])
        if families:
            print(f"  Ransomware Families: {', '.join(families)}")
        
        techniques = finding.get('attack_techniques', [])
        if techniques:
            print(f"  Attack Techniques: {', '.join(techniques)}")
        
        industries = finding.get('target_industries', [])
        if industries:
            print(f"  Target Industries: {', '.join(industries)}")
        
        indicators = finding.get('technical_indicators', [])
        if indicators:
            print(f"  Technical Indicators: {', '.join(indicators)}")

def main():
    """Main function to view LLM analysis results"""
    import argparse
    
    parser = argparse.ArgumentParser(description='View LLM analysis results from S3')
    parser.add_argument('--bucket', help='S3 bucket name (defaults to processed bucket)')
    parser.add_argument('--limit', type=int, default=5, help='Maximum number of results to show')
    parser.add_argument('--detailed', action='store_true', help='Show detailed findings')
    parser.add_argument('--latest', action='store_true', help='Show only the latest result')
    
    args = parser.parse_args()
    
    print("🔍 LLM Analysis Results Viewer")
    print("=" * 50)
    
    # Get analysis results
    results = list_llm_analysis_results(args.bucket, args.limit)
    
    if not results:
        print("❌ No LLM analysis results found in S3")
        print("Run the LLM analysis workflow first to generate results.")
        return
    
    # Show results
    if args.latest:
        results = results[:1]
    
    print(f"\n📊 Showing {len(results)} LLM analysis result(s)")
    
    for result in results:
        display_analysis_summary(result)
        
        if args.detailed:
            display_detailed_findings(result)
    
    print(f"\n✅ Found {len(results)} LLM analysis results in S3")
    print("\n💡 Tips:")
    print("  • Use --detailed to see detailed threat intelligence findings")
    print("  • Use --latest to see only the most recent analysis")
    print("  • Use --limit N to see the last N analyses")

if __name__ == "__main__":
    main()
