"""
Windows Credential Manager Implementation
"""

import os
import subprocess
import json
from typing import List, Dict, Any
from .base import CredentialCollector


class WindowsCredentialCollector(CredentialCollector):
    """
    Windows Credential Manager collector
    """
    
    def __init__(self):
        """Initialize the Windows credential collector"""
        super().__init__()
        
    def collect(self) -> List[Dict[str, Any]]:
        """
        Collect Windows credentials using multiple methods
        
        Returns:
            List of credential entries
        """
        if not self._check_permissions():
            return []
            
        credentials = []
        
        # Method 1: Use cmdkey command
        credentials.extend(self._collect_via_cmdkey())
        
        # Method 2: Check registry for credential entries
        credentials.extend(self._collect_via_registry())
        
        # Method 3: Check credential files
        credentials.extend(self._collect_via_files())
        
        # Save results
        if credentials:
            self._save_results(credentials, "credentials.json")
            
        return credentials
    
    def get_credential_type(self) -> str:
        """
        Get credential type identifier
        
        Returns:
            "windows_credential"
        """
        return "windows_credential"
    
    def _collect_via_cmdkey(self) -> List[Dict[str, Any]]:
        """
        Collect credentials using cmdkey command
        
        Returns:
            List of credential entries from cmdkey
        """
        credentials = []
        
        try:
            result = subprocess.run(
                ["cmdkey", "/list"], 
                capture_output=True, 
                text=True, 
                encoding='utf-8',
                errors='ignore'
            )
            
            if result.returncode == 0:
                lines = result.stdout.split('\n')
                current_entry = {}
                
                for line in lines:
                    line = line.strip()
                    if line.startswith("Target:"):
                        if current_entry:
                            credentials.append(current_entry)
                        current_entry = {"target": line.replace("Target:", "").strip()}
                    elif line.startswith("Type:") and current_entry:
                        current_entry["type"] = line.replace("Type:", "").strip()
                    elif line.startswith("User:") and current_entry:
                        current_entry["user"] = line.replace("User:", "").strip()
                        
                if current_entry:
                    credentials.append(current_entry)
                    
        except Exception as e:
            print(f"Error collecting credentials via cmdkey: {e}")
            
        return credentials
    
    def _collect_via_registry(self) -> List[Dict[str, Any]]:
        """
        Collect credential information from registry
        
        Returns:
            List of credential entries from registry
        """
        credentials = []
        
        try:
            import winreg
            
            # Check HKCU\Software\Microsoft\Credentials
            key_path = r"Software\Microsoft\Credentials"
            
            try:
                with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key_path) as key:
                    i = 0
                    while True:
                        try:
                            subkey_name = winreg.EnumKey(key, i)
                            subkey_path = f"{key_path}\\{subkey_name}"
                            
                            try:
                                with winreg.OpenKey(winreg.HKEY_CURRENT_USER, subkey_path) as subkey:
                                    entry = {
                                        "target": subkey_name,
                                        "source": "registry",
                                        "type": "credential_entry"
                                    }
                                    
                                    # Try to read common values
                                    try:
                                        target_name, _ = winreg.QueryValueEx(subkey, "TargetName")
                                        entry["target_name"] = target_name
                                    except:
                                        pass
                                        
                                    try:
                                        cred_type, _ = winreg.QueryValueEx(subkey, "Type")
                                        entry["credential_type"] = cred_type
                                    except:
                                        pass
                                        
                                    credentials.append(entry)
                                    
                            except:
                                pass
                                
                            i += 1
                        except WindowsError:
                            break
                            
            except:
                pass
                
        except ImportError:
            print("winreg module not available (not running on Windows)")
            
        return credentials
    
    def _collect_via_files(self) -> List[Dict[str, Any]]:
        """
        Collect credential file information
        
        Returns:
            List of credential file entries
        """
        credentials = []
        
        if not self.context_info or not self.context_info.appdata_path:
            return credentials
            
        cred_dir = os.path.join(self.context_info.appdata_path, "Microsoft", "Credentials")
        
        if os.path.exists(cred_dir):
            try:
                for filename in os.listdir(cred_dir):
                    file_path = os.path.join(cred_dir, filename)
                    if os.path.isfile(file_path):
                        entry = {
                            "file": filename,
                            "source": "file",
                            "type": "credential_file",
                            "size": os.path.getsize(file_path)
                        }
                        credentials.append(entry)
                        
            except Exception as e:
                print(f"Error reading credential files: {e}")
                
        return credentials