"""
无线网络信息获取实现
"""

import os
from typing import List
from diona.system.sensitive.info.WirelessNetworkInfo import WirelessNetworkInfoInterface
from diona.system.sensitive.info.models.WirelessNetworkInfo import WirelessNetworkInfo, WirelessNetworkProfile
from diona.system.sensitive.info.constants.WirelessNetworkInfoConstants import WirelessNetworkInfoConstants
from diona.system.sensitive.core import get_info_store_instance
from diona.system.sensitive.runcontext.utils import execute_command


class WirelessNetworkInfoImpl(WirelessNetworkInfoInterface):
    """无线网络信息获取实现"""
    
    def __init__(self):
        """
        初始化无线网络信息获取器
        """
        self.info_store = get_info_store_instance()
    
    def get_wireless_network_info(self) -> WirelessNetworkInfo:
        """
        获取无线网络信息
        
        Returns:
            WirelessNetworkInfo: 无线网络信息对象
        """
        if not self.can_execute():
            return WirelessNetworkInfo(
                error_message="Insufficient permissions to get wireless network info"
            )
        
        try:
            # 执行 netsh wlan show profiles 命令获取所有配置文件
            result = execute_command(
                WirelessNetworkInfoConstants.NETSH_WLAN_SHOW_PROFILES_COMMAND,
                encoding=WirelessNetworkInfoConstants.DEFAULT_ENCODING
            )
            
            if not result.success:
                return WirelessNetworkInfo(
                    error_message=f"{WirelessNetworkInfoConstants.ERROR_EXECUTING_NETSH}: {result.error}"
                )
            
            # 解析配置文件列表
            profile_names = self._parse_profiles_output(result.output)
            
            # 获取每个配置文件的详细信息
            profiles = []
            for profile_name in profile_names:
                profile = self._get_profile_details(profile_name)
                if profile:
                    profiles.append(profile)
            
            # 尝试从配置文件目录读取额外信息
            self._read_wlan_profiles_from_directory(profiles)
            
            return WirelessNetworkInfo(profiles=profiles)
            
        except Exception as e:
            return WirelessNetworkInfo(
                error_message=f"{WirelessNetworkInfoConstants.ERROR_PARSING_OUTPUT}: {str(e)}"
            )
    
    def can_execute(self) -> bool:
        """
        检查是否可以执行无线网络信息获取
        
        Returns:
            bool: 是否可以执行
        """
        context_info = self.info_store.get_context_info()
        if context_info:
            # 无线网络信息获取对所有用户开放
            return True
        return False
    
    def _parse_profiles_output(self, output: str) -> List[str]:
        """
        解析 netsh wlan show profiles 命令输出
        
        Args:
            output: 命令输出
        
        Returns:
            List[str]: 配置文件名称列表
        """
        profile_names = []
        lines = output.split('\n')
        
        for line in lines:
            line = line.strip()
            if WirelessNetworkInfoConstants.PROFILE_NAME_PATTERN in line:
                profile_name = line.split(WirelessNetworkInfoConstants.PROFILE_NAME_PATTERN, 1)[1].strip()
                profile_names.append(profile_name)
        
        return profile_names
    
    def _get_profile_details(self, profile_name: str) -> WirelessNetworkProfile:
        """
        获取单个配置文件的详细信息
        
        Args:
            profile_name: 配置文件名称
        
        Returns:
            WirelessNetworkProfile: 无线网络配置文件对象
        """
        # 构建命令
        command = WirelessNetworkInfoConstants.NETSH_WLAN_SHOW_PROFILE_COMMAND.copy()
        command[3] = profile_name
        
        # 执行命令
        result = execute_command(
            command,
            encoding=WirelessNetworkInfoConstants.DEFAULT_ENCODING
        )
        
        if not result.success:
            return None
        
        # 解析输出
        profile = WirelessNetworkProfile()
        lines = result.output.split('\n')
        
        for line in lines:
            line = line.strip()
            
            if WirelessNetworkInfoConstants.SSID_NAME_PATTERN in line:
                profile.ssid = self._extract_value(line, WirelessNetworkInfoConstants.SSID_NAME_PATTERN)
            elif WirelessNetworkInfoConstants.AUTHENTICATION_PATTERN in line:
                profile.authentication = self._extract_value(line, WirelessNetworkInfoConstants.AUTHENTICATION_PATTERN)
            elif WirelessNetworkInfoConstants.ENCRYPTION_PATTERN in line:
                profile.encryption = self._extract_value(line, WirelessNetworkInfoConstants.ENCRYPTION_PATTERN)
            elif WirelessNetworkInfoConstants.KEY_CONTENT_PATTERN in line:
                profile.key_content = self._extract_value(line, WirelessNetworkInfoConstants.KEY_CONTENT_PATTERN)
        
        return profile
    
    def _read_wlan_profiles_from_directory(self, profiles: List[WirelessNetworkProfile]) -> None:
        """
        从 WLAN 配置文件目录读取配置文件信息
        
        Args:
            profiles: 无线网络配置文件列表
        """
        try:
            # 检查配置文件目录是否存在
            if os.path.exists(WirelessNetworkInfoConstants.WLAN_PROFILES_DIR):
                # 遍历接口目录
                for interface_dir in os.listdir(WirelessNetworkInfoConstants.WLAN_PROFILES_DIR):
                    interface_path = os.path.join(WirelessNetworkInfoConstants.WLAN_PROFILES_DIR, interface_dir)
                    if os.path.isdir(interface_path):
                        # 遍历配置文件
                        for profile_file in os.listdir(interface_path):
                            if profile_file.endswith('.xml'):
                                profile_path = os.path.join(interface_path, profile_file)
                                # 尝试匹配到对应的配置文件
                                for profile in profiles:
                                    if profile.ssid and profile.ssid in profile_file:
                                        profile.profile_path = profile_path
                                        break
        except Exception as e:
            print(f"Error reading WLAN profiles from directory: {e}")
    
    def _extract_value(self, line: str, pattern: str) -> str:
        """
        从行中提取值
        
        Args:
            line: 包含值的行
            pattern: 模式字符串
        
        Returns:
            str: 提取的值
        """
        if pattern in line:
            return line.split(pattern, 1)[1].strip()
        return None