"""
Registry Analysis Exporter

Exports registry analysis results to persistent storage using the project storage system.
"""

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

from diona.project.storage import ProjectStorage
from .models import RegistryAnalysisResult, RecentDocsData, ShellBagsData, RecentDocsEntry, ShellBagEntry


class RegistryExporter:
    """Exporter for registry analysis results."""
    
    def __init__(self):
        self.storage = ProjectStorage()
        self.regedit_module = "windows"
        self.regedit_dir = "regedit"
        
        # Initialize storage directories
        self._ensure_storage_directories()
    
    def _ensure_storage_directories(self):
        """Ensure required storage directories exist."""
        # Create regedit directory in ~/.diona/project/windows/regedit/
        regedit_path = self.storage.get_path(
            self.regedit_module, 
            self.regedit_dir, 
            "project"
        )
        os.makedirs(regedit_path, exist_ok=True)
    
    def _convert_recent_docs_to_dict(self, recent_docs: RecentDocsData) -> Dict[str, Any]:
        """Convert RecentDocsData to serializable dictionary."""
        return {
            "status": recent_docs.status.value,
            "error_message": recent_docs.error_message,
            "extension_groups": {
                ext: [
                    {
                        "file_name": entry.file_name,
                        "value_name": entry.value_name,
                        "timestamp": entry.timestamp.isoformat() if entry.timestamp else None,
                        "file_extension": entry.file_extension,
                        "registry_key_name": entry.registry_key_name,
                        "actual_file_path": entry.actual_file_path
                    }
                    for entry in entries
                ]
                for ext, entries in recent_docs.extension_groups.items()
            },
            "applications": [
                {
                    "file_name": entry.file_name,
                    "value_name": entry.value_name,
                    "timestamp": entry.timestamp.isoformat() if entry.timestamp else None,
                    "file_extension": entry.file_extension,
                    "registry_key_name": entry.registry_key_name,
                    "actual_file_path": entry.actual_file_path
                }
                for entry in recent_docs.applications
            ]
        }
    
    def _convert_shellbags_to_dict(self, shellbags: ShellBagsData) -> Dict[str, Any]:
        """Convert ShellBagsData to serializable dictionary."""
        return {
            "status": shellbags.status.value,
            "error_message": shellbags.error_message,
            "bag_locations": {
                location: [
                    {
                        "path": entry.path,
                        "slot_index": entry.slot_index,
                        "view_mode": entry.view_mode,
                        "timestamp": entry.timestamp.isoformat() if entry.timestamp else None,
                        "item_data": entry.item_data
                    }
                    for entry in entries
                ]
                for location, entries in shellbags.bag_locations.items()
            }
        }
    
    def _convert_result_to_dict(self, result: RegistryAnalysisResult) -> Dict[str, Any]:
        """Convert RegistryAnalysisResult to serializable dictionary."""
        return {
            "analysis_timestamp": result.analysis_timestamp.isoformat(),
            "recent_docs": self._convert_recent_docs_to_dict(result.recent_docs),
            "shellbags": self._convert_shellbags_to_dict(result.shellbags),
            "context_info": {
                "username": result.context_info.username if result.context_info else None,
                "context_type": result.context_info.context_type if result.context_info else None,
                "profile_path": result.context_info.profile_path if result.context_info else None,
                "appdata_path": result.context_info.appdata_path if result.context_info else None,
                "localappdata_path": result.context_info.localappdata_path if result.context_info else None
            } if result.context_info else None
        }
    
    def export_result(self, result: RegistryAnalysisResult, filename: Optional[str] = None) -> str:
        """
        Export registry analysis result to persistent storage.
        
        Args:
            result: The registry analysis result to export
            filename: Optional filename (default: timestamp-based)
            
        Returns:
            Path to the exported file
        """
        if filename is None:
            # Generate timestamp-based filename
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"registry_analysis_{timestamp}.json"
        
        # Convert result to serializable format
        result_dict = self._convert_result_to_dict(result)
        
        # Save to storage
        file_path = self.storage.get_path(
            self.regedit_module, 
            f"{self.regedit_dir}/{filename}", 
            "project"
        )
        
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(result_dict, f, indent=2, ensure_ascii=False)
        
        return file_path
    
    def export_recent_docs(self, recent_docs: RecentDocsData, filename: Optional[str] = None) -> str:
        """
        Export only RecentDocs analysis result.
        
        Args:
            recent_docs: The RecentDocs analysis result to export
            filename: Optional filename (default: timestamp-based)
            
        Returns:
            Path to the exported file
        """
        if filename is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"recent_docs_{timestamp}.json"
        
        # Convert to serializable format
        recent_docs_dict = self._convert_recent_docs_to_dict(recent_docs)
        
        # Save to storage
        file_path = self.storage.get_path(
            self.regedit_module, 
            f"{self.regedit_dir}/{filename}", 
            "project"
        )
        
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(recent_docs_dict, f, indent=2, ensure_ascii=False)
        
        return file_path
    
    def export_shellbags(self, shellbags: ShellBagsData, filename: Optional[str] = None) -> str:
        """
        Export only ShellBags analysis result.
        
        Args:
            shellbags: The ShellBags analysis result to export
            filename: Optional filename (default: timestamp-based)
            
        Returns:
            Path to the exported file
        """
        if filename is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"shellbags_{timestamp}.json"
        
        # Convert to serializable format
        shellbags_dict = self._convert_shellbags_to_dict(shellbags)
        
        # Save to storage
        file_path = self.storage.get_path(
            self.regedit_module, 
            f"{self.regedit_dir}/{filename}", 
            "project"
        )
        
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump(shellbags_dict, f, indent=2, ensure_ascii=False)
        
        return file_path
    
    def list_exports(self) -> list:
        """
        List all exported registry analysis files.
        
        Returns:
            List of exported filenames
        """
        regedit_path = self.storage.get_path(
            self.regedit_module, 
            self.regedit_dir, 
            "project"
        )
        
        if os.path.exists(regedit_path):
            files = []
            for filename in os.listdir(regedit_path):
                if filename.endswith('.json'):
                    files.append(filename)
            return sorted(files)
        else:
            return []
    
    def load_export(self, filename: str) -> Dict[str, Any]:
        """
        Load an exported registry analysis file.
        
        Args:
            filename: The filename to load
            
        Returns:
            The loaded data as dictionary
        """
        file_path = self.storage.get_path(
            self.regedit_module, 
            f"{self.regedit_dir}/{filename}", 
            "project"
        )
        
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        else:
            raise FileNotFoundError(f"Export file not found: {filename}")
    
    def delete_export(self, filename: str) -> bool:
        """
        Delete an exported registry analysis file.
        
        Args:
            filename: The filename to delete
            
        Returns:
            True if successful, False otherwise
        """
        file_path = self.storage.get_path(
            self.regedit_module, 
            f"{self.regedit_dir}/{filename}", 
            "project"
        )
        
        if os.path.exists(file_path):
            os.remove(file_path)
            return True
        else:
            return False