import sys
import os
import subprocess
import shutil
import re
from pathlib import Path
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QHBoxLayout, QWidget, QPushButton, QLineEdit, QLabel, QComboBox, QScrollArea, QGridLayout, QMessageBox, QGroupBox
from PyQt6.QtCore import Qt

class SystemSetupTool(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Windows Setup Tool")
        self.setGeometry(100, 100, 800, 600)
        self.adapter_info = {}
        
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        main_layout = QVBoxLayout()
        
        computer_group = QGroupBox("1. 컴퓨터명 변경")
        computer_layout = QHBoxLayout()
        self.computer_name_input = QLineEdit()
        computer_layout.addWidget(QLabel("컴퓨터명:"))
        computer_layout.addWidget(self.computer_name_input)
        computer_layout.addWidget(QPushButton("변경", clicked=self.change_computer_name))
        computer_group.setLayout(computer_layout)
        main_layout.addWidget(computer_group)
        
        workgroup_group = QGroupBox("2. 작업 그룹명 변경")
        workgroup_layout = QHBoxLayout()
        self.workgroup_input = QLineEdit()
        workgroup_layout.addWidget(QLabel("작업 그룹명:"))
        workgroup_layout.addWidget(self.workgroup_input)
        workgroup_layout.addWidget(QPushButton("변경", clicked=self.change_workgroup))
        workgroup_group.setLayout(workgroup_layout)
        main_layout.addWidget(workgroup_group)
        
        network_group = QGroupBox("3. 네트워크 IP 변경")
        network_layout = QVBoxLayout()
        
        adapter_layout = QHBoxLayout()
        adapter_layout.addWidget(QLabel("네트워크 어댑터:"))
        self.adapter_combo = QComboBox()
        self.load_network_adapters()
        adapter_layout.addWidget(self.adapter_combo)
        adapter_layout.addWidget(QPushButton("새로고침", clicked=self.load_network_adapters))
        network_layout.addLayout(adapter_layout)
        
        ip_layout = QGridLayout()
        self.ip_input = QLineEdit()
        self.subnet_input = QLineEdit("255.255.255.0")
        self.gateway_input = QLineEdit()
        self.dns1_input = QLineEdit("8.8.8.8")
        self.dns2_input = QLineEdit("8.8.4.4")
        
        ip_layout.addWidget(QLabel("IP 주소:"), 0, 0)
        ip_layout.addWidget(self.ip_input, 0, 1)
        ip_layout.addWidget(QLabel("서브넷 마스크:"), 1, 0)
        ip_layout.addWidget(self.subnet_input, 1, 1)
        ip_layout.addWidget(QLabel("게이트웨이:"), 2, 0)
        ip_layout.addWidget(self.gateway_input, 2, 1)
        ip_layout.addWidget(QLabel("DNS 1:"), 3, 0)
        ip_layout.addWidget(self.dns1_input, 3, 1)
        ip_layout.addWidget(QLabel("DNS 2:"), 4, 0)
        ip_layout.addWidget(self.dns2_input, 4, 1)
        
        network_layout.addLayout(ip_layout)
        
        button_layout = QHBoxLayout()
        button_layout.addWidget(QPushButton("IP 설정", clicked=self.set_network_ip))
        button_layout.addWidget(QPushButton("DHCP 자동 설정", clicked=self.set_dhcp))
        network_layout.addLayout(button_layout)
        
        network_group.setLayout(network_layout)
        main_layout.addWidget(network_group)
        
        app1_group = QGroupBox("4. App_1 폴더 실행 파일")
        self.app1_layout = QGridLayout()
        self.load_app1_shortcuts()
        app1_scroll = QScrollArea()
        app1_widget = QWidget()
        app1_widget.setLayout(self.app1_layout)
        app1_scroll.setWidget(app1_widget)
        app1_scroll.setWidgetResizable(True)
        app1_scroll.setMaximumHeight(150)
        app1_vbox = QVBoxLayout()
        app1_vbox.addWidget(app1_scroll)
        app1_group.setLayout(app1_vbox)
        main_layout.addWidget(app1_group)
        
        app2_group = QGroupBox("5. App_2 폴더 복사")
        app2_layout = QVBoxLayout()
        app2_layout.addWidget(QPushButton("App_2 폴더를 Documents로 복사", clicked=self.copy_app2_folders))
        app2_group.setLayout(app2_layout)
        main_layout.addWidget(app2_group)
        
        main_layout.addStretch()
        central_widget.setLayout(main_layout)
    
    def change_computer_name(self):
        name = self.computer_name_input.text()
        if name:
            try:
                subprocess.run(f'wmic computersystem where name="%COMPUTERNAME%" call rename name="{name}"', shell=True, check=True)
                QMessageBox.information(self, "성공", f"컴퓨터명이 {name}으로 변경되었습니다. 재부팅이 필요합니다.")
            except:
                QMessageBox.critical(self, "오류", "컴퓨터명 변경 실패")
    
    def change_workgroup(self):
        workgroup = self.workgroup_input.text()
        if workgroup:
            try:
                subprocess.run(f'wmic computersystem where name="%COMPUTERNAME%" call joindomainorworkgroup name="{workgroup}"', shell=True, check=True)
                QMessageBox.information(self, "성공", f"작업 그룹이 {workgroup}으로 변경되었습니다.")
            except:
                QMessageBox.critical(self, "오류", "작업 그룹 변경 실패")
    
    def load_network_adapters(self):
        self.adapter_combo.clear()
        self.adapter_info = {}
        
        try:
            found_adapters = False
            
            # Method 1: Try multiple encoding combinations with PowerShell
            encodings_to_try = ['utf-8', 'cp949', 'cp1252', 'utf-16le']
            
            for encoding in encodings_to_try:
                if found_adapters:
                    break
                    
                try:
                    ps_cmd = '''
                    $OutputEncoding = [System.Text.Encoding]::UTF8
                    [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
                    Get-NetAdapter | Where-Object {$_.Status -eq "Up"} | ForEach-Object {
                        $connectionName = $_.Name
                        $index = $_.InterfaceIndex
                        $hardwareDesc = $_.InterfaceDescription
                        $type = if ($_.MediaType -like "*802.11*" -or $_.InterfaceDescription -like "*Wireless*" -or $_.InterfaceDescription -like "*Wi-Fi*") {"무선"} else {"유선"}
                        Write-Output "$index|$connectionName|$hardwareDesc|$type"
                    }
                    '''
                    
                    result = subprocess.run(['powershell', '-Command', ps_cmd], 
                                          capture_output=True, text=True, encoding=encoding)
                    
                    if result.returncode == 0 and result.stdout.strip():
                        lines = [line.strip() for line in result.stdout.split('\n') if line.strip()]
                        for line in lines:
                            if '|' in line:
                                parts = line.split('|', 3)
                                if len(parts) >= 3:
                                    index, connection_name, hardware_desc, adapter_type = parts[0], parts[1], parts[2], parts[3] if len(parts) > 3 else "유선"
                                    # Check if hardware description contains valid characters (not just ?)
                                    if hardware_desc and not all(c in '?' for c in hardware_desc.strip()):
                                        # Use hardware description as primary name, with connection name as secondary info
                                        display_name = f"[{adapter_type}] {hardware_desc} ({connection_name}) - Index: {index}"
                                        self.adapter_combo.addItem(display_name)
                                        self.adapter_info[display_name] = {
                                            'name': connection_name,
                                            'index': index,
                                            'description': hardware_desc,
                                            'hardware': hardware_desc,
                                            'type': adapter_type
                                        }
                                        found_adapters = True
                except:
                    continue
            
            # Method 2: Enhanced registry + hardware description approach
            if not found_adapters:
                try:
                    ps_cmd_reg = '''
                    $adapters = Get-NetAdapter | Where-Object {$_.Status -eq "Up"}
                    foreach ($adapter in $adapters) {
                        $index = $adapter.InterfaceIndex
                        $connectionName = $adapter.Name
                        $hardwareDesc = $adapter.InterfaceDescription
                        $guid = $adapter.InterfaceGuid
                        $type = if ($adapter.MediaType -like "*802.11*" -or $adapter.InterfaceDescription -like "*Wireless*" -or $adapter.InterfaceDescription -like "*Wi-Fi*") {"무선"} else {"유선"}
                        
                        # Try to get connection name from registry
                        $regPath = "HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\$guid\\Connection"
                        try {
                            $regName = (Get-ItemProperty -Path $regPath -Name "Name" -ErrorAction SilentlyContinue).Name
                            if ($regName) {
                                $connectionName = $regName
                            }
                        } catch {}
                        
                        Write-Output "$index|$connectionName|$hardwareDesc|$type"
                    }
                    '''
                    
                    result_reg = subprocess.run(['powershell', '-Command', ps_cmd_reg], 
                                              capture_output=True, text=True, encoding='utf-8')
                    
                    if result_reg.returncode == 0 and result_reg.stdout.strip():
                        lines = [line.strip() for line in result_reg.stdout.split('\n') if line.strip()]
                        for line in lines:
                            if '|' in line:
                                parts = line.split('|', 3)
                                if len(parts) >= 3:
                                    index, connection_name, hardware_desc, adapter_type = parts[0], parts[1], parts[2], parts[3] if len(parts) > 3 else "유선"
                                    display_name = f"[{adapter_type}] {hardware_desc} ({connection_name}) - Index: {index}"
                                    self.adapter_combo.addItem(display_name)
                                    self.adapter_info[display_name] = {
                                        'name': connection_name,
                                        'index': index,
                                        'description': hardware_desc,
                                        'hardware': hardware_desc,
                                        'type': adapter_type
                                    }
                                    found_adapters = True
                except:
                    pass
            
            # Method 3: WMI-based hardware description fallback
            if not found_adapters:
                try:
                    ps_cmd_wmi = '''
                    Get-WmiObject Win32_NetworkAdapter | Where-Object {$_.NetEnabled -eq $true -and $_.PhysicalAdapter -eq $true} | ForEach-Object {
                        $index = $_.InterfaceIndex
                        $name = $_.NetConnectionID
                        $desc = $_.Name
                        $manufacturer = $_.Manufacturer
                        $type = if ($_.Name -like "*Wireless*" -or $_.Name -like "*Wi-Fi*" -or $_.Name -like "*802.11*") {"무선"} else {"유선"}
                        if (-not $name) { $name = "네트워크 연결 $index" }
                        Write-Output "$index|$name|$desc|$manufacturer|$type"
                    }
                    '''
                    
                    result_wmi = subprocess.run(['powershell', '-Command', ps_cmd_wmi], 
                                              capture_output=True, text=True, encoding='utf-8')
                    
                    if result_wmi.returncode == 0 and result_wmi.stdout.strip():
                        lines = [line.strip() for line in result_wmi.stdout.split('\n') if line.strip()]
                        for line in lines:
                            if '|' in line:
                                parts = line.split('|', 4)
                                if len(parts) >= 4:
                                    index, connection_name, hardware_desc, manufacturer, adapter_type = parts[0], parts[1], parts[2], parts[3], parts[4] if len(parts) > 4 else "유선"
                                    
                                    # Create a comprehensive display name
                                    if manufacturer and manufacturer.strip() and manufacturer != "null":
                                        display_name = f"[{adapter_type}] {hardware_desc} - {manufacturer} ({connection_name}) - Index: {index}"
                                    else:
                                        display_name = f"[{adapter_type}] {hardware_desc} ({connection_name}) - Index: {index}"
                                    
                                    self.adapter_combo.addItem(display_name)
                                    self.adapter_info[display_name] = {
                                        'name': connection_name,
                                        'index': index,
                                        'description': hardware_desc,
                                        'hardware': hardware_desc,
                                        'manufacturer': manufacturer,
                                        'type': adapter_type
                                    }
                                    found_adapters = True
                except:
                    pass
            
            # Method 4: Last resort - enumerate by index only
            if not found_adapters:
                try:
                    ps_cmd_index = '''
                    Get-NetAdapter | Where-Object {$_.Status -eq "Up"} | ForEach-Object {
                        $index = $_.InterfaceIndex
                        Write-Output "$index"
                    }
                    '''
                    
                    result_index = subprocess.run(['powershell', '-Command', ps_cmd_index], 
                                                capture_output=True, text=True, encoding='utf-8')
                    
                    if result_index.returncode == 0 and result_index.stdout.strip():
                        indexes = [line.strip() for line in result_index.stdout.split('\n') if line.strip().isdigit()]
                        for index in indexes:
                            adapter_name = f"네트워크 어댑터 {index}"
                            display_name = f"{adapter_name} (Index: {index})"
                            self.adapter_combo.addItem(display_name)
                            self.adapter_info[display_name] = {
                                'name': adapter_name,
                                'index': index,
                                'description': f"네트워크 인터페이스 {index}"
                            }
                            found_adapters = True
                except:
                    pass
                    
        except Exception as e:
            QMessageBox.critical(self, "오류", f"네트워크 어댑터 로드 실패: {str(e)}")
    
    def validate_ip(self, ip):
        pattern = r'^(\d{1,3}\.){3}\d{1,3}$'
        if not re.match(pattern, ip):
            return False
        parts = ip.split('.')
        return all(0 <= int(part) <= 255 for part in parts)
    
    def set_network_ip(self):
        selected_adapter = self.adapter_combo.currentText()
        ip = self.ip_input.text().strip()
        subnet = self.subnet_input.text().strip()
        gateway = self.gateway_input.text().strip()
        dns1 = self.dns1_input.text().strip()
        dns2 = self.dns2_input.text().strip()
        
        if not selected_adapter:
            QMessageBox.warning(self, "경고", "네트워크 어댑터를 선택해주세요.")
            return
        
        if not all([ip, subnet, gateway]):
            QMessageBox.warning(self, "경고", "IP 주소, 서브넷 마스크, 게이트웨이를 모두 입력해주세요.")
            return
        
        if not self.validate_ip(ip):
            QMessageBox.warning(self, "경고", "올바른 IP 주소를 입력해주세요.")
            return
        
        if not self.validate_ip(subnet):
            QMessageBox.warning(self, "경고", "올바른 서브넷 마스크를 입력해주세요.")
            return
        
        if not self.validate_ip(gateway):
            QMessageBox.warning(self, "경고", "올바른 게이트웨이를 입력해주세요.")
            return
        
        if dns1 and not self.validate_ip(dns1):
            QMessageBox.warning(self, "경고", "올바른 DNS 1을 입력해주세요.")
            return
        
        if dns2 and not self.validate_ip(dns2):
            QMessageBox.warning(self, "경고", "올바른 DNS 2를 입력해주세요.")
            return
        
        # Get adapter info
        adapter_info = self.adapter_info.get(selected_adapter)
        if not adapter_info:
            QMessageBox.critical(self, "오류", "선택한 어댑터의 정보를 찾을 수 없습니다.")
            return
        
        adapter_name = adapter_info['name']
        adapter_index = adapter_info['index']
        
        try:
            # Calculate prefix length from subnet mask
            prefix_length = sum([bin(int(x)).count('1') for x in subnet.split('.')])
            
            # Method 1: Use interface index for more reliable configuration
            ps_script = f'''
            try {{
                Write-Output "Step 1: Removing existing IP configuration..."
                # Remove existing IP configuration
                Remove-NetIPAddress -InterfaceIndex {adapter_index} -Confirm:$false -ErrorAction SilentlyContinue
                Remove-NetRoute -InterfaceIndex {adapter_index} -Confirm:$false -ErrorAction SilentlyContinue
                
                Write-Output "Step 2: Setting IP address..."
                # Set new IP configuration (without gateway first)
                New-NetIPAddress -InterfaceIndex {adapter_index} -IPAddress "{ip}" -PrefixLength {prefix_length} -ErrorAction Stop
                
                Write-Output "Step 3: Adding default gateway..."
                # Add default gateway separately
                New-NetRoute -InterfaceIndex {adapter_index} -DestinationPrefix "0.0.0.0/0" -NextHop "{gateway}" -ErrorAction Stop
                
                Write-Output "Step 4: Setting DNS servers..."
                # Set DNS servers
                if ("{dns1}" -ne "") {{
                    if ("{dns2}" -ne "") {{
                        Set-DnsClientServerAddress -InterfaceIndex {adapter_index} -ServerAddresses @("{dns1}","{dns2}") -ErrorAction Stop
                    }} else {{
                        Set-DnsClientServerAddress -InterfaceIndex {adapter_index} -ServerAddresses "{dns1}" -ErrorAction Stop
                    }}
                }}
                
                Write-Output "SUCCESS: IP configuration completed"
            }} catch {{
                Write-Output "ERROR: $($_.Exception.Message)"
            }}
            '''
            
            result = subprocess.run(['powershell', '-Command', ps_script], 
                                  capture_output=True, text=True, encoding='utf-8')
            
            if "SUCCESS:" in result.stdout:
                QMessageBox.information(self, "성공", "IP 설정이 완료되었습니다.")
            elif "ERROR:" in result.stdout:
                error_msg = result.stdout.split("ERROR:")[-1].strip()
                
                # Fallback: Try with netsh using interface index
                try:
                    cmd1 = f'netsh interface ip set address {adapter_index} static {ip} {subnet} {gateway}'
                    result1 = subprocess.run(cmd1, shell=True, capture_output=True, text=True, encoding='utf-8')
                    
                    if result1.returncode == 0:
                        if dns1:
                            cmd2 = f'netsh interface ip set dns {adapter_index} static {dns1}'
                            subprocess.run(cmd2, shell=True, capture_output=True, text=True, encoding='utf-8')
                        if dns2:
                            cmd3 = f'netsh interface ip add dns {adapter_index} {dns2} index=2'
                            subprocess.run(cmd3, shell=True, capture_output=True, text=True, encoding='utf-8')
                        QMessageBox.information(self, "성공", "IP 설정이 완료되었습니다 (백업 방법 사용).")
                    else:
                        QMessageBox.critical(self, "오류", f"IP 설정 실패: {error_msg}")
                except Exception as fallback_error:
                    QMessageBox.critical(self, "오류", f"IP 설정 실패: {error_msg}\n백업 방법도 실패: {str(fallback_error)}")
            else:
                QMessageBox.critical(self, "오류", f"알 수 없는 오류가 발생했습니다.\n출력: {result.stdout}\n오류: {result.stderr}")
                
        except Exception as e:
            QMessageBox.critical(self, "오류", f"IP 설정 실패: {str(e)}")
    
    def set_dhcp(self):
        selected_adapter = self.adapter_combo.currentText()
        
        if not selected_adapter:
            QMessageBox.warning(self, "경고", "네트워크 어댑터를 선택해주세요.")
            return
        
        # Get adapter info
        adapter_info = self.adapter_info.get(selected_adapter)
        if not adapter_info:
            QMessageBox.critical(self, "오류", "선택한 어댑터의 정보를 찾을 수 없습니다.")
            return
        
        adapter_name = adapter_info['name']
        adapter_index = adapter_info['index']
        
        try:
            # PowerShell script to set DHCP - use connection name instead of index for better compatibility
            ps_script = f'''
            try {{
                Write-Output "Step 1: Removing static IP configuration..."
                # Remove existing static IP configuration
                Remove-NetIPAddress -InterfaceAlias "{adapter_name}" -Confirm:$false -ErrorAction SilentlyContinue
                Remove-NetRoute -InterfaceAlias "{adapter_name}" -Confirm:$false -ErrorAction SilentlyContinue
                
                Write-Output "Step 2: Enabling DHCP for IP address..."
                # Enable DHCP for IP address
                Set-NetIPInterface -InterfaceAlias "{adapter_name}" -Dhcp Enabled -ErrorAction Stop
                
                Write-Output "Step 3: Enabling DHCP for DNS..."
                # Enable DHCP for DNS
                Set-DnsClientServerAddress -InterfaceAlias "{adapter_name}" -ResetServerAddresses -ErrorAction Stop
                
                Write-Output "Step 4: Restarting network interface..."
                # Restart the network interface to apply DHCP
                Restart-NetAdapter -Name "{adapter_name}" -ErrorAction Stop
                
                Write-Output "SUCCESS: DHCP configuration completed"
            }} catch {{
                Write-Output "ERROR: $($_.Exception.Message)"
            }}
            '''
            
            result = subprocess.run(['powershell', '-Command', ps_script], 
                                  capture_output=True, text=True, encoding='utf-8')
            
            if "SUCCESS:" in result.stdout:
                QMessageBox.information(self, "성공", "DHCP 자동 설정이 완료되었습니다.")
                # Clear the input fields since they're no longer relevant
                self.ip_input.clear()
                self.gateway_input.clear()
            elif "ERROR:" in result.stdout:
                error_msg = result.stdout.split("ERROR:")[-1].strip()
                
                # Fallback: Try with netsh
                try:
                    cmd1 = f'netsh interface ip set address {adapter_index} dhcp'
                    result1 = subprocess.run(cmd1, shell=True, capture_output=True, text=True, encoding='utf-8')
                    
                    cmd2 = f'netsh interface ip set dns {adapter_index} dhcp'
                    result2 = subprocess.run(cmd2, shell=True, capture_output=True, text=True, encoding='utf-8')
                    
                    if result1.returncode == 0 and result2.returncode == 0:
                        QMessageBox.information(self, "성공", "DHCP 자동 설정이 완료되었습니다 (백업 방법 사용).")
                        self.ip_input.clear()
                        self.gateway_input.clear()
                    else:
                        QMessageBox.critical(self, "오류", f"DHCP 설정 실패: {error_msg}")
                except Exception as fallback_error:
                    QMessageBox.critical(self, "오류", f"DHCP 설정 실패: {error_msg}\n백업 방법도 실패: {str(fallback_error)}")
            else:
                QMessageBox.critical(self, "오류", f"알 수 없는 오류가 발생했습니다.\n출력: {result.stdout}\n오류: {result.stderr}")
                
        except Exception as e:
            QMessageBox.critical(self, "오류", f"DHCP 설정 실패: {str(e)}")
    
    def load_app1_shortcuts(self):
        for i in reversed(range(self.app1_layout.count())):
            self.app1_layout.itemAt(i).widget().deleteLater()
        
        # Use the directory where app.py is located (same directory as set.py)
        script_dir = Path(__file__).parent.resolve()
        app1_path = script_dir / "app_1"
        
        # Auto-create app_1 folder if it doesn't exist
        if not app1_path.exists():
            try:
                app1_path.mkdir(parents=True, exist_ok=True)
                # Create a sample README file
                readme_file = app1_path / "README.txt"
                readme_file.write_text(
                    "App_1 폴더입니다.\n"
                    "이 폴더에 실행파일(.exe), 바로가기(.lnk), 배치파일(.bat, .cmd)을 넣으면\n"
                    "프로그램에서 버튼으로 실행할 수 있습니다.\n\n"
                    "지원 파일 형식:\n"
                    "- .exe (실행파일)\n"
                    "- .lnk (바로가기)\n"
                    "- .bat, .cmd (배치파일)\n",
                    encoding='utf-8'
                )
            except Exception as e:
                QMessageBox.warning(self, "경고", f"App_1 폴더 생성 실패: {str(e)}")
        
        if app1_path.exists():
            row, col = 0, 0
            executable_files = []
            for file in app1_path.iterdir():
                if file.suffix in ['.exe', '.lnk', '.bat', '.cmd']:
                    executable_files.append(file)
            
            if executable_files:
                for file in executable_files:
                    btn = QPushButton(file.stem)
                    btn.clicked.connect(lambda checked, f=str(file): self.run_app(f))
                    self.app1_layout.addWidget(btn, row, col)
                    col += 1
                    if col > 3:
                        col = 0
                        row += 1
            else:
                # No executable files found, show message
                info_label = QLabel("실행 가능한 파일이 없습니다.\napp_1 폴더에 .exe, .lnk, .bat, .cmd 파일을 넣어주세요.")
                info_label.setStyleSheet("color: gray; font-style: italic;")
                info_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
                self.app1_layout.addWidget(info_label, 0, 0, 1, 4)
    
    def run_app(self, file_path):
        try:
            os.startfile(file_path)
        except:
            QMessageBox.critical(self, "오류", f"{file_path} 실행 실패")
    
    def copy_app2_folders(self):
        # Use the directory where app.py is located (same directory as set.py)
        script_dir = Path(__file__).parent.resolve()
        app2_path = script_dir / "app_2"
        documents_path = Path.home() / "Documents"
        
        # Auto-create app_2 folder if it doesn't exist
        if not app2_path.exists():
            try:
                app2_path.mkdir(parents=True, exist_ok=True)
                # Create sample files and README
                readme_file = app2_path / "README.txt"
                readme_file.write_text(
                    "App_2 폴더입니다.\n"
                    "이 폴더 안의 파일들이 사용자의 Documents 폴더로 복사됩니다.\n\n"
                    "사용 방법:\n"
                    "1. 이 폴더(app_2) 안에 복사하고 싶은 파일들을 넣습니다.\n"
                    "2. 'App_2 폴더를 Documents로 복사' 버튼을 클릭합니다.\n"
                    "3. 파일들이 C:\\Users\\사용자명\\Documents로 복사됩니다.\n\n"
                    "주의: 기존에 같은 이름의 파일이 있으면 덮어쓰여집니다.\n",
                    encoding='utf-8'
                )
                
                sample_file = app2_path / "샘플파일.txt"
                sample_file.write_text(
                    "이것은 샘플 파일입니다.\n"
                    "복사 기능을 테스트해보세요.\n"
                    "이 파일은 Documents 폴더로 복사됩니다.",
                    encoding='utf-8'
                )
                
                QMessageBox.information(self, "정보", f"App_2 폴더가 생성되었습니다:\n{app2_path}\n\n샘플 파일과 README 파일이 포함되어 있습니다.")
            except Exception as e:
                QMessageBox.warning(self, "경고", f"App_2 폴더 생성 실패: {str(e)}")
        
        if app2_path.exists():
            try:
                files_copied = []
                for item in app2_path.iterdir():
                    # 파일만 복사 (폴더는 제외)
                    if item.is_file() and not item.name.startswith('.'):
                        dest = documents_path / item.name
                        # 기존 파일이 있으면 덮어쓰기
                        shutil.copy2(item, dest)
                        files_copied.append(item.name)
                
                if files_copied:
                    QMessageBox.information(self, "성공", f"다음 파일들이 {documents_path}로 복사되었습니다:\n\n" + "\n".join(f"• {file}" for file in files_copied))
                else:
                    QMessageBox.information(self, "정보", "복사할 파일이 없습니다.\napp_2 폴더에 복사하고 싶은 파일들을 넣어주세요.")
            except Exception as e:
                QMessageBox.critical(self, "오류", f"파일 복사 실패: {str(e)}")
        else:
            QMessageBox.warning(self, "경고", "App_2 폴더가 존재하지 않습니다.")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = SystemSetupTool()
    window.show()
    sys.exit(app.exec())