"""
网络配置信息获取实现
"""

from typing import List, Optional
from diona.system.sensitive.info.NetworkConfigInfo import NetworkConfigInfoInterface
from diona.system.sensitive.info.models.NetworkConfigInfo import (
    NetworkConfigInfo, NetworkAdapterInfo, NetworkConnectionInfo, DnsCacheEntry
)
from diona.system.sensitive.info.constants.NetworkConfigInfoConstants import NetworkConfigInfoConstants
from diona.system.sensitive.core import get_info_store_instance
from diona.system.sensitive.runcontext.utils import execute_command


class NetworkConfigInfoImpl(NetworkConfigInfoInterface):
    """网络配置信息获取实现"""
    
    def __init__(self):
        """
        初始化网络配置信息获取器
        """
        self.info_store = get_info_store_instance()
    
    def get_network_config_info(self) -> NetworkConfigInfo:
        """
        获取网络配置信息
        
        Returns:
            NetworkConfigInfo: 网络配置信息对象
        """
        if not self.can_execute():
            return NetworkConfigInfo(
                error_message="Insufficient permissions to get network config info"
            )
        
        try:
            # 执行 ipconfig /all 命令获取网络适配器信息
            ipconfig_result = execute_command(
                NetworkConfigInfoConstants.IPCONFIG_ALL_COMMAND,
                encoding=NetworkConfigInfoConstants.DEFAULT_ENCODING
            )
            
            # 执行 ipconfig /displaydns 命令获取 DNS 缓存信息
            dns_result = execute_command(
                NetworkConfigInfoConstants.IPCONFIG_DISPLAYDNS_COMMAND,
                encoding=NetworkConfigInfoConstants.DEFAULT_ENCODING
            )
            
            # 构建网络配置信息对象
            config_info = NetworkConfigInfo()
            
            # 解析网络适配器信息
            if ipconfig_result.success:
                config_info.adapters = self._parse_ipconfig_output(ipconfig_result.output)
            else:
                config_info.error_message = f"{NetworkConfigInfoConstants.ERROR_EXECUTING_IPCONFIG}: {ipconfig_result.error}"
            
            # 解析 DNS 缓存信息
            if dns_result.success:
                config_info.dns_cache = self._parse_dns_output(dns_result.output)
            
            return config_info
            
        except Exception as e:
            return NetworkConfigInfo(
                error_message=f"{NetworkConfigInfoConstants.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_ipconfig_output(self, output: str) -> List[NetworkAdapterInfo]:
        """
        解析 ipconfig /all 命令输出
        
        Args:
            output: 命令输出
        
        Returns:
            List[NetworkAdapterInfo]: 网络适配器信息列表
        """
        adapters = []
        lines = output.split('\n')
        current_adapter = None
        
        for line in lines:
            # 保留原始行格式，不进行strip()，因为缩进很重要
            
            # 检查是否是适配器行
            if '适配器' in line:
                # 开始新的适配器
                if current_adapter:
                    adapters.append(current_adapter)
                # 提取适配器名称
                adapter_name = line.split('适配器', 1)[1].strip()
                # 移除末尾的冒号
                if adapter_name.endswith(':'):
                    adapter_name = adapter_name[:-1]
                current_adapter = NetworkAdapterInfo(name=adapter_name, dns_servers=[])
            elif current_adapter:
                # 解析适配器详细信息
                if '描述. . . . . . . . . . . . . . . :' in line:
                    current_adapter.description = line.split('描述. . . . . . . . . . . . . . . :', 1)[1].strip()
                elif '物理地址. . . . . . . . . . . . . :' in line:
                    current_adapter.physical_address = line.split('物理地址. . . . . . . . . . . . . :', 1)[1].strip()
                elif 'DHCP 已启用 . . . . . . . . . . . :' in line:
                    current_adapter.dhcp_enabled = line.split('DHCP 已启用 . . . . . . . . . . . :', 1)[1].strip()
                elif '自动配置已启用. . . . . . . . . . :' in line:
                    current_adapter.autoconfiguration_enabled = line.split('自动配置已启用. . . . . . . . . . :', 1)[1].strip()
                elif '本地链接 IPv6 地址. . . . . . . . :' in line:
                    current_adapter.link_local_ipv6_address = line.split('本地链接 IPv6 地址. . . . . . . . :', 1)[1].strip()
                elif 'IPv4 地址 . . . . . . . . . . . . :' in line:
                    current_adapter.ipv4_address = line.split('IPv4 地址 . . . . . . . . . . . . :', 1)[1].strip()
                elif '子网掩码  . . . . . . . . . . . . :' in line:
                    current_adapter.subnet_mask = line.split('子网掩码  . . . . . . . . . . . . :', 1)[1].strip()
                elif '默认网关. . . . . . . . . . . . . :' in line:
                    current_adapter.default_gateway = line.split('默认网关. . . . . . . . . . . . . :', 1)[1].strip()
                elif 'DHCP 服务器 . . . . . . . . . . . :' in line:
                    current_adapter.dhcp_server = line.split('DHCP 服务器 . . . . . . . . . . . :', 1)[1].strip()
                elif 'DNS 服务器  . . . . . . . . . . . :' in line:
                    dns_server = line.split('DNS 服务器  . . . . . . . . . . . :', 1)[1].strip()
                    if dns_server and current_adapter.dns_servers is not None:
                        current_adapter.dns_servers.append(dns_server)
                elif '获得租约的时间  . . . . . . . . . :' in line:
                    current_adapter.lease_obtained = line.split('获得租约的时间  . . . . . . . . . :', 1)[1].strip()
                elif '租约过期的时间  . . . . . . . . . :' in line:
                    current_adapter.lease_expires = line.split('租约过期的时间  . . . . . . . . . :', 1)[1].strip()
        
        # 添加最后一个适配器
        if current_adapter:
            adapters.append(current_adapter)
        
        return adapters
    
    def _parse_dns_output(self, output: str) -> List[DnsCacheEntry]:
        """
        解析 ipconfig /displaydns 命令输出
        
        Args:
            output: 命令输出
        
        Returns:
            List[DnsCacheEntry]: DNS 缓存条目列表
        """
        entries = []
        lines = output.split('\n')
        current_entry = None
        current_answers = []
        
        for line in lines:
            line = line.strip()
            
            if NetworkConfigInfoConstants.RECORD_NAME_PATTERN in line:
                # 开始新的 DNS 条目
                if current_entry:
                    current_entry.answers = current_answers
                    entries.append(current_entry)
                current_entry = DnsCacheEntry()
                current_answers = []
                current_entry.record_name = self._extract_value(line, NetworkConfigInfoConstants.RECORD_NAME_PATTERN)
            elif current_entry:
                if NetworkConfigInfoConstants.RECORD_TYPE_PATTERN in line:
                    current_entry.record_type = self._extract_value(line, NetworkConfigInfoConstants.RECORD_TYPE_PATTERN)
                elif NetworkConfigInfoConstants.TIME_TO_LIVE_PATTERN in line:
                    current_entry.time_to_live = self._extract_value(line, NetworkConfigInfoConstants.TIME_TO_LIVE_PATTERN)
                elif NetworkConfigInfoConstants.DATA_LENGTH_PATTERN in line:
                    current_entry.data_length = self._extract_value(line, NetworkConfigInfoConstants.DATA_LENGTH_PATTERN)
                elif NetworkConfigInfoConstants.SECTION_PATTERN in line:
                    current_entry.section = self._extract_value(line, NetworkConfigInfoConstants.SECTION_PATTERN)
                elif NetworkConfigInfoConstants.ANSWER_SECTION_PATTERN in line:
                    # 开始答案部分
                    pass
                elif NetworkConfigInfoConstants.NAME_PATTERN in line:
                    # 开始新的答案
                    if current_answers and isinstance(current_answers[-1], dict):
                        current_answers.append({})
                    else:
                        current_answers.append({})
                    current_answers[-1]['name'] = self._extract_value(line, NetworkConfigInfoConstants.NAME_PATTERN)
                elif current_answers and isinstance(current_answers[-1], dict):
                    if NetworkConfigInfoConstants.TYPE_PATTERN in line:
                        current_answers[-1]['type'] = self._extract_value(line, NetworkConfigInfoConstants.TYPE_PATTERN)
                    elif NetworkConfigInfoConstants.DATA_PATTERN in line:
                        current_answers[-1]['data'] = self._extract_value(line, NetworkConfigInfoConstants.DATA_PATTERN)
        
        # 添加最后一个 DNS 条目
        if current_entry:
            current_entry.answers = current_answers
            entries.append(current_entry)
        
        return entries
    
    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