"""
Command Line Interface for Registry Analysis

Provides command-line tools for analyzing Windows registry data and exporting results.
"""

import argparse
import json
import os
import sys
from datetime import datetime
from typing import Optional, Dict, Any

from .analyzer import RegistryAnalyzer
from .exporter import RegistryExporter
from .models import RegistryAnalysisResult


def analyze_and_export(export_filename: Optional[str] = None, 
                      export_dir: Optional[str] = None) -> Dict[str, Any]:
    """
    Perform registry analysis and export results.
    
    Args:
        export_filename: Optional filename for export
        export_dir: Optional directory for export (default: project storage)
        
    Returns:
        Analysis result summary
    """
    print("=== Windows Registry Analysis ===")
    
    # Create analyzer and exporter
    analyzer = RegistryAnalyzer()
    exporter = RegistryExporter()
    
    # Perform analysis
    print("🔍 Analyzing RecentDocs registry...")
    result = analyzer.analyze_all()
    
    # Display analysis summary
    print(f"✅ RecentDocs analysis: {result.recent_docs.status.value}")
    print(f"✅ ShellBags analysis: {result.shellbags.status.value}")
    
    if result.recent_docs.status.value == "success":
        total_files = sum(len(entries) for entries in result.recent_docs.extension_groups.values())
        print(f"📄 Found {total_files} recent files across {len(result.recent_docs.extension_groups)} file types")
    
    if result.shellbags.status.value == "success":
        total_entries = sum(len(entries) for entries in result.shellbags.bag_locations.values())
        print(f"📁 Found {total_entries} folder history entries")
    
    # Export results
    if export_filename:
        export_path = exporter.export_result(result, export_filename)
    else:
        export_path = exporter.export_result(result)
    
    print(f"💾 Results exported to: {export_path}")
    
    # Return summary
    return {
        "recent_docs_status": result.recent_docs.status.value,
        "shellbags_status": result.shellbags.status.value,
        "recent_docs_files": sum(len(entries) for entries in result.recent_docs.extension_groups.values()) if result.recent_docs.status.value == "success" else 0,
        "shellbags_entries": sum(len(entries) for entries in result.shellbags.bag_locations.values()) if result.shellbags.status.value == "success" else 0,
        "export_path": export_path,
        "analysis_timestamp": result.analysis_timestamp.isoformat()
    }


def list_exports() -> list:
    """List all exported registry analysis files."""
    exporter = RegistryExporter()
    files = exporter.list_exports()
    
    print("=== Exported Registry Analysis Files ===")
    if files:
        for i, filename in enumerate(files, 1):
            print(f"{i}. {filename}")
    else:
        print("No exported files found.")
    
    return files


def view_export(filename: str) -> Dict[str, Any]:
    """View the contents of an exported registry analysis file."""
    exporter = RegistryExporter()
    
    try:
        data = exporter.load_export(filename)
        
        print(f"=== Contents of {filename} ===")
        print(json.dumps(data, indent=2, ensure_ascii=False))
        
        return data
    except FileNotFoundError as e:
        print(f"❌ Error: {e}")
        return {}


def delete_export(filename: str) -> bool:
    """Delete an exported registry analysis file."""
    exporter = RegistryExporter()
    
    success = exporter.delete_export(filename)
    
    if success:
        print(f"✅ Deleted: {filename}")
    else:
        print(f"❌ File not found: {filename}")
    
    return success


def main():
    """Command line interface main function."""
    parser = argparse.ArgumentParser(
        description="Windows Registry Analysis Tool",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
使用示例:
  # 执行注册表分析并导出结果
  python -m diona.system.sensitive.regedit.cli analyze
  
  # 执行分析并指定导出文件名
  python -m diona.system.sensitive.regedit.cli analyze --export my_analysis.json
  
  # 列出所有导出的文件
  python -m diona.system.sensitive.regedit.cli list
  
  # 查看导出的文件内容
  python -m diona.system.sensitive.regedit.cli view --file registry_analysis_20240303_120000.json
  
  # 删除导出的文件
  python -m diona.system.sensitive.regedit.cli delete --file registry_analysis_20240303_120000.json
  
  # 使用函数接口（在Python代码中）
  from diona.system.sensitive.regedit.cli import analyze_and_export
  
  result = analyze_and_export("my_analysis.json")
  print(f"分析完成: {result['recent_docs_files']} 个最近文件")
        """
    )
    
    subparsers = parser.add_subparsers(dest='command', help='Command to execute')
    
    # Analyze command
    analyze_parser = subparsers.add_parser('analyze', help='Analyze registry and export results')
    analyze_parser.add_argument('--export', '-e', help='Export filename (optional)')
    
    # List command
    list_parser = subparsers.add_parser('list', help='List exported files')
    
    # View command
    view_parser = subparsers.add_parser('view', help='View exported file contents')
    view_parser.add_argument('--file', '-f', required=True, help='Filename to view')
    
    # Delete command
    delete_parser = subparsers.add_parser('delete', help='Delete exported file')
    delete_parser.add_argument('--file', '-f', required=True, help='Filename to delete')
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return
    
    try:
        if args.command == 'analyze':
            analyze_and_export(args.export)
        elif args.command == 'list':
            list_exports()
        elif args.command == 'view':
            view_export(args.file)
        elif args.command == 'delete':
            delete_export(args.file)
    except Exception as e:
        print(f"❌ Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()