"""
工具函数模块
"""

import subprocess
import os
from typing import Optional

from .models import CommandResult
from .constants import CommandPatterns, EnvironmentVariables


def execute_command(command: list, encoding: str = 'utf-8') -> CommandResult:
    """执行系统命令"""
    try:
        result = subprocess.run(
            command, 
            capture_output=True, 
            text=True, 
            encoding=encoding, 
            errors='ignore'
        )
        return CommandResult(
            success=result.returncode == 0,
            output=result.stdout,
            error=result.stderr if result.returncode != 0 else None
        )
    except Exception as e:
        return CommandResult(
            success=False,
            output="",
            error=str(e)
        )


def extract_sid_from_whoami_output(output: str) -> Optional[str]:
    """从whoami命令输出中提取SID"""
    lines = output.strip().split('\n')
    if len(lines) > 1:
        for line in lines:
            if CommandPatterns.SID_PATTERN in line:
                parts = line.strip().split()
                for part in parts:
                    if part.startswith(CommandPatterns.SID_PATTERN):
                        return part
    return None


def extract_groups_from_net_user_output(output: str) -> list:
    """从net user命令输出中提取用户组"""
    groups = []
    lines = output.split('\n')
    
    for line in lines:
        line = line.strip()
        if (CommandPatterns.LOCAL_GROUP_MEMBERS_ZH in line or 
            CommandPatterns.LOCAL_GROUP_MEMBERS_EN in line):
            
            # 提取组名
            parts = line.split('*')
            for part in parts[1:]:  # 跳过第一个空的部分
                group_name = part.strip()
                if group_name and not group_name.startswith('None'):
                    groups.append(group_name)
            break
    
    return groups


def get_session_type() -> Optional[str]:
    """获取会话类型"""
    try:
        session_name = os.environ.get(EnvironmentVariables.SESSIONNAME)
        if session_name:
            if session_name.startswith(CommandPatterns.RDP_SESSION_PREFIX):
                return CommandPatterns.RDP_SESSION_PREFIX
            elif session_name == CommandPatterns.CONSOLE_SESSION_NAME:
                return CommandPatterns.CONSOLE_SESSION_NAME
            else:
                return CommandPatterns.OTHER
        return None
    except Exception:
        return None