import ctypes
import os
import getpass

from .constants import ContextType, SessionType, GroupConstants, EnvironmentVariables
from .models import ContextInfo, UserGroup
from .utils import execute_command, extract_sid_from_whoami_output, extract_groups_from_net_user_output, get_session_type


class RunContext:
    """Run Context Detection Class"""
    
    def __init__(self):
        self.context_type = None
        self.username = None
        self.sid = None
        self.profile_path = None
        self.appdata_path = None
        self.localappdata_path = None
        self.groups = []
        self.session_type = None
    
    def verify_execution_context(self) -> str:
        """Verify execution context, return current user permission type"""
        try:
            # Check if running as administrator
            if self._is_admin():
                self.context_type = ContextType.ADMINISTRATOR
                return self.context_type
            
            # Get current user information
            self.username = getpass.getuser()
            self.sid = self._get_user_sid(self.username)
            self.groups = self._get_user_groups(self.username)
            
            # Check if belongs to administrators group
            for group in self.groups:
                if (group.name == GroupConstants.ADMINISTRATORS_GROUP_NAME or 
                    group.sid == GroupConstants.ADMINISTRATORS_GROUP_SID):
                    self.context_type = ContextType.ADMINISTRATOR
                    return self.context_type
            
            # Get user environment variables
            self.profile_path = os.environ.get(EnvironmentVariables.USERPROFILE)
            self.appdata_path = os.environ.get(EnvironmentVariables.APPDATA)
            self.localappdata_path = os.environ.get(EnvironmentVariables.LOCALAPPDATA)
            
            # Identify session type
            self.session_type = get_session_type()
            
            self.context_type = ContextType.STANDARD_USER
            return self.context_type
            
        except Exception as e:
            print(f"Error verifying execution context: {e}")
            return ContextType.STANDARD_USER
    
    def _is_admin(self):
        """Check if currently running as administrator"""
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            return False
    
    def _get_user_sid(self, username: str) -> str:
        """Get user SID"""
        try:
            # Use utility function to execute whoami command
            result = execute_command(['whoami', '/user'])
            if result.success:
                return extract_sid_from_whoami_output(result.output)
            return None
        except Exception as e:
            print(f"Error getting user SID: {e}")
            return None
    
    def _get_user_groups(self, username: str) -> list:
        """Get user groups that the user belongs to"""
        groups = []
        try:
            # Use utility function to execute net user command
            result = execute_command(['net', 'user', username], encoding='gbk')
            if result.success:
                group_names = extract_groups_from_net_user_output(result.output)
                for group_name in group_names:
                    groups.append(UserGroup(
                        name=group_name,
                        domain='',
                        sid=''
                    ))
            return groups
        except Exception as e:
            print(f"Error getting user groups: {e}")
            pass
        return groups
    
    def get_context_info(self) -> ContextInfo:
        """Get complete context information"""
        if self.context_type is None:
            self.verify_execution_context()
        
        return ContextInfo(
            context_type=self.context_type,
            username=self.username,
            sid=self.sid,
            profile_path=self.profile_path,
            appdata_path=self.appdata_path,
            localappdata_path=self.localappdata_path,
            groups=self.groups,
            session_type=self.session_type
        )