# CCLS Games CLI Tool
# Complete Version with Setup, Search, and Get functionality

# Configuration
$baseUrl = "https://games.ccls.icu"
$cliApiUrl = "$baseUrl/CLI"
$settingsFolder = ".\settings"
$credentialsFile = "$settingsFolder\credentials.dat"
$settingsFile = "$settingsFolder\settings.json" # Using JSON instead of INI for simplicity

# Ensure settings directory exists
if (-not (Test-Path $settingsFolder)) {
    New-Item -Path $settingsFolder -ItemType Directory | Out-Null
}

# Initialize or load settings
function Initialize-Settings {
    if (-not (Test-Path $settingsFile)) {
        # Create default settings file
        $defaultSettings = @{
            RememberLogin = $false
            DownloadPath = ".\downloads"
            TempDownloadPath = ".\tmp"
            HasCompletedSetup = $false
        }
        $defaultSettings | ConvertTo-Json | Set-Content -Path $settingsFile
    }
    
    # Load settings
    $settings = Get-Content -Path $settingsFile | ConvertFrom-Json
    return $settings
}

# Save settings
function Save-Settings($settings) {
    $settings | ConvertTo-Json | Set-Content -Path $settingsFile
}

# Store credentials securely
function Save-Credentials($username, $password) {
    $credentials = @{
        Username = $username
        Password = $password
    } | ConvertTo-Json
    
    # Simple encryption (replace with more secure method if needed)
    $securePassword = ConvertTo-SecureString -String $credentials -AsPlainText -Force
    $encryptedText = ConvertFrom-SecureString -SecureString $securePassword
    
    # Save to file
    $encryptedText | Set-Content -Path $credentialsFile
}

# Load stored credentials
function Get-StoredCredentials {
    if (Test-Path $credentialsFile) {
        try {
            $encryptedText = Get-Content -Path $credentialsFile
            $securePassword = ConvertTo-SecureString -String $encryptedText
            $credentials = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
                [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePassword)
            )
            return $credentials | ConvertFrom-Json
        }
        catch {
            Write-Host "Error reading credentials: $($_.Exception.Message)" -ForegroundColor Red
            return $null
        }
    }
    return $null
}

# Run setup process
function Start-Setup {
    Clear-Host
    Write-Host "CCLS Games CLI Setup" -ForegroundColor Green
    Write-Host "=====================" -ForegroundColor Green
    Write-Host "Please configure the following settings:`n" -ForegroundColor Cyan
    
    $settings = Initialize-Settings
    
    # Get game installation directory
    $validPath = $false
    while (-not $validPath) {
        Write-Host "Set your games default installation directory: " -ForegroundColor Yellow -NoNewline
        $downloadPath = Read-Host
        
        if ([string]::IsNullOrWhiteSpace($downloadPath)) {
            Write-Host "Please enter a valid directory path." -ForegroundColor Red
        }
        else {
            # Create directory if it doesn't exist
            if (-not (Test-Path $downloadPath)) {
                try {
                    New-Item -ItemType Directory -Path $downloadPath -Force | Out-Null
                    $validPath = $true
                }
                catch {
                    Write-Host "Error creating directory: $($_.Exception.Message)" -ForegroundColor Red
                }
            }
            else {
                $validPath = $true
            }
        }
    }
    
    # Get temporary download directory
    $validTempPath = $false
    while (-not $validTempPath) {
        Write-Host "Set the temporary directory of downloading files before they have finished downloading: " -ForegroundColor Yellow -NoNewline
        $tempDownloadPath = Read-Host
        
        if ([string]::IsNullOrWhiteSpace($tempDownloadPath)) {
            Write-Host "Please enter a valid directory path." -ForegroundColor Red
        }
        else {
            # Create directory if it doesn't exist
            if (-not (Test-Path $tempDownloadPath)) {
                try {
                    New-Item -ItemType Directory -Path $tempDownloadPath -Force | Out-Null
                    $validTempPath = $true
                }
                catch {
                    Write-Host "Error creating directory: $($_.Exception.Message)" -ForegroundColor Red
                }
            }
            else {
                $validTempPath = $true
            }
        }
    }
    
    # Update settings
    $settings.DownloadPath = $downloadPath
    $settings.TempDownloadPath = $tempDownloadPath
    $settings.HasCompletedSetup = $true
    Save-Settings -settings $settings
    
    Clear-Host
    Write-Host "Great, you have now completed the setup. Type 'help' for a list of commands to get you started." -ForegroundColor Green
}

# Validate username against server
function Test-Username($username) {
    $params = @{
        Uri = "$cliApiUrl/username_check.php"
        Method = "POST"
        Headers = @{
            "User-Agent" = "CCLS-CLI/1.0"
        }
        Body = @{
            username = $username
        }
    }
    
    try {
        $response = Invoke-RestMethod @params
        return $response.exists
    }
    catch {
        Write-Host "Error connecting to the server: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# Validate password against server
function Test-Password($username, $password) {
    $params = @{
        Uri = "$cliApiUrl/password_check.php"
        Method = "POST"
        Headers = @{
            "User-Agent" = "CCLS-CLI/1.0"
        }
        Body = @{
            username = $username
            password = $password
        }
    }
    
    try {
        $response = Invoke-RestMethod @params
        return $response.success
    }
    catch {
        Write-Host "Error connecting to the server: $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# Try auto-login with stored credentials
function Start-AutoLogin {
    $credentials = Get-StoredCredentials
    if ($credentials -ne $null) {
        Write-Host "Attempting to login with stored credentials..." -ForegroundColor Gray
        
        if (Test-Password -username $credentials.Username -password $credentials.Password) {
            Write-Host "Auto-login successful!" -ForegroundColor Green
            return @{
                Success = $true
                Username = $credentials.Username
            }
        }
        else {
            Write-Host "Stored credentials are no longer valid." -ForegroundColor Yellow
            # Remove invalid credentials
            if (Test-Path $credentialsFile) {
                Remove-Item -Path $credentialsFile -Force
            }
        }
    }
    
    return @{
        Success = $false
    }
}

# Manual login process
function Start-ManualLogin {
    $maxAttempts = 3
    $attempts = 0
    
    while ($attempts -lt $maxAttempts) {
        Write-Host "`nUsername: " -ForegroundColor Cyan -NoNewline
        $username = Read-Host
        
        # Check if username exists
        Write-Host "Checking username..." -ForegroundColor Gray
        if (Test-Username -username $username) {
            Write-Host "Username found!" -ForegroundColor Green
            
            Write-Host "Password: " -ForegroundColor Cyan -NoNewline
            $password = Read-Host -AsSecureString
            $passwordPlain = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
                [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password)
            )
            
            Write-Host "Validating password..." -ForegroundColor Gray
            if (Test-Password -username $username -password $passwordPlain) {
                Write-Host "Login successful!" -ForegroundColor Green
                
                # Ask if user wants to save credentials
                Write-Host "`nDo you want to remember your login info for next time? (Y/N)" -ForegroundColor Yellow
                $rememberLogin = Read-Host
                
                if ($rememberLogin.ToLower() -eq "y") {
                    Save-Credentials -username $username -password $passwordPlain
                    $settings = Initialize-Settings
                    $settings.RememberLogin = $true
                    Save-Settings -settings $settings
                    Write-Host "Login information saved." -ForegroundColor Green
                }
                
                return @{
                    Success = $true
                    Username = $username
                }
            }
            else {
                Write-Host "Incorrect password, please try again." -ForegroundColor Red
                $attempts++
            }
        }
        else {
            Write-Host "Username not found, please try again." -ForegroundColor Red
            $attempts++
        }
    }
    
    Write-Host "Too many failed login attempts. Please try again later." -ForegroundColor Red
    return @{
        Success = $false
    }
}

# Search for game information by CG number
function Search-Game($cgNumber) {
    # Validate CG number format
    if ($cgNumber -notmatch "^cg\d{4}$") {
        Write-Host "Invalid CG number format. Please use format 'cg0000'." -ForegroundColor Red
        return
    }
    
    try {
        # Construct the URL for the game JSON file
        $gameJsonUrl = "$cliApiUrl/search.php?id=$cgNumber"
        
        # Attempt to fetch the game information
        $params = @{
            Uri = $gameJsonUrl
            Method = "GET"
            Headers = @{
                "User-Agent" = "CCLS-CLI/1.0"
            }
        }
        
        Write-Host "Searching for game information..." -ForegroundColor Gray
        
        # Fetch game data from server
        try {
            $response = Invoke-RestMethod @params
            
            # Check if the request was successful
            if (-not $response.success) {
                Write-Host "Error: $($response.message)" -ForegroundColor Red
                return
            }
            
            $gameInfo = $response
        }
        catch {
            Write-Host "Error fetching game information: $($_.Exception.Message)" -ForegroundColor Red
            return
        }
        
        # Display game information in a formatted way
        Clear-Host
        Write-Host "Game Information for $($gameInfo.name) ($($gameInfo.id))" -ForegroundColor Green
        Write-Host "=======================================================" -ForegroundColor Green
        
        Write-Host "`nDescription:" -ForegroundColor Cyan
        Write-Host $gameInfo.description
        
        if ($gameInfo.safety_score -or $gameInfo.safety_level) {
            Write-Host "`nSafety:" -ForegroundColor Cyan
            if ($gameInfo.safety_score) { Write-Host "Score: $($gameInfo.safety_score)" }
            if ($gameInfo.safety_level) { Write-Host "Level: $($gameInfo.safety_level)" }
        }
        
        Write-Host "`nDetails:" -ForegroundColor Cyan
        if ($gameInfo.size) { Write-Host "Size: $($gameInfo.size)" }
        if ($gameInfo.version -and $gameInfo.version -ne "") { Write-Host "Version: $($gameInfo.version)" }
        
        if (($gameInfo.online -and $gameInfo.online -ne "") -or 
            ($gameInfo.steam -and $gameInfo.steam -ne "") -or 
            ($gameInfo.epic -and $gameInfo.epic -ne "")) {
            Write-Host "`nAvailability:" -ForegroundColor Cyan
            if ($gameInfo.online -and $gameInfo.online -ne "") { Write-Host "Online: $($gameInfo.online)" }
            if ($gameInfo.steam -and $gameInfo.steam -ne "") { Write-Host "Steam: $($gameInfo.steam)" }
            if ($gameInfo.epic -and $gameInfo.epic -ne "") { Write-Host "Epic: $($gameInfo.epic)" }
        }
        
        if ($gameInfo.false_av -and $gameInfo.false_av -ne "") {
            Write-Host "`nNote: " -ForegroundColor Yellow -NoNewline
            Write-Host "This game may trigger false antivirus alerts: $($gameInfo.false_av)"
        }
        
        if ($gameInfo.system_requirements) {
            Write-Host "`nSystem Requirements:" -ForegroundColor Cyan
            
            if ($gameInfo.system_requirements.minimum) {
                Write-Host "Minimum:" -ForegroundColor Yellow
                foreach ($prop in $gameInfo.system_requirements.minimum.PSObject.Properties) {
                    Write-Host "  $($prop.Name): $($prop.Value)"
                }
            }
            
            if ($gameInfo.system_requirements.recommended) {
                Write-Host "`nRecommended:" -ForegroundColor Yellow
                foreach ($prop in $gameInfo.system_requirements.recommended.PSObject.Properties) {
                    Write-Host "  $($prop.Name): $($prop.Value)"
                }
            }
        }
        
        Write-Host "`nPress any key to return to the main menu..." -ForegroundColor Gray
        $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
    catch {
        Write-Host "An error occurred while processing game information: $($_.Exception.Message)" -ForegroundColor Red
        Write-Host "Press any key to return to the main menu..." -ForegroundColor Gray
        $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

# Function to format file size
function Format-FileSize {
    param ([string]$Size)
    
    if ([string]::IsNullOrEmpty($Size)) {
        return "Unknown Size"
    }
    
    # Extract numeric part and unit
    if ($Size -match "(\d+\.?\d*)\s*(GB|MB|KB|B)") {
        $value = [double]$matches[1]
        $unit = $matches[2]
        
        return "$value $unit"
    }
    
    return $Size
}

# Function to download and extract a game
function Get-Game($cgNumber) {
    # Validate CG number format
    if ($cgNumber -notmatch "^cg\d{4}$") {
        Write-Host "Invalid CG number format. Please use format 'cg0000'." -ForegroundColor Red
        return
    }
    
    # Check if setup has been completed
    $settings = Initialize-Settings
    if (-not $settings.HasCompletedSetup) {
        Write-Host "ALERT, you must run the 'setup' command before downloading games." -ForegroundColor Red
        return
    }
    
    # Ensure download directories exist
    if (-not (Test-Path $settings.DownloadPath)) {
        try {
            New-Item -ItemType Directory -Path $settings.DownloadPath -Force | Out-Null
        }
        catch {
            Write-Host "Error creating download directory: $($_.Exception.Message)" -ForegroundColor Red
            return
        }
    }
    
    if (-not (Test-Path $settings.TempDownloadPath)) {
        try {
            New-Item -ItemType Directory -Path $settings.TempDownloadPath -Force | Out-Null
        }
        catch {
            Write-Host "Error creating temporary download directory: $($_.Exception.Message)" -ForegroundColor Red
            return
        }
    }
    
    # Fetch game download information
    try {
        $gameInfoUrl = "$cliApiUrl/get.php?id=$cgNumber"
        
        $params = @{
            Uri = $gameInfoUrl
            Method = "GET"
            Headers = @{
                "User-Agent" = "CCLS-CLI/1.0"
            }
        }
        
        Write-Host "Fetching game download information..." -ForegroundColor Gray
        
        $response = Invoke-RestMethod @params
        
        if (-not $response.success) {
            Write-Host "Error: $($response.message)" -ForegroundColor Red
            return
        }
        
        $gameName = $response.name
        $gameId = $response.id
        $downloadUrl = $response.download_url
        $gameSize = $response.size
        
        # Create download file name from URL
        $fileName = Split-Path -Path $downloadUrl -Leaf
        if ([string]::IsNullOrEmpty($fileName)) {
            $fileName = "$gameId.7z"
        }
        
        $downloadPath = Join-Path -Path $settings.TempDownloadPath -ChildPath $fileName
        
        # Confirm download with user
        Clear-Host
        Write-Host "Game: $gameName ($gameId)" -ForegroundColor Green
        Write-Host "Size: $gameSize" -ForegroundColor Yellow
        Write-Host "Download URL: $downloadUrl" -ForegroundColor Cyan
        Write-Host "Download Location: $downloadPath" -ForegroundColor Cyan
        Write-Host "Extract Location: $($settings.DownloadPath)" -ForegroundColor Cyan
        Write-Host "`nALERT, the get command will start the downloading process of the game specified, to stop it do 'Ctrl C'" -ForegroundColor Red
        Write-Host "`nDo you want to proceed with the download? (Y/N)" -ForegroundColor Yellow
        
        $confirmation = Read-Host
        if ($confirmation.ToLower() -ne "y") {
            Write-Host "Download cancelled by user." -ForegroundColor Yellow
            return
        }
        
        # Start download
        $webClient = New-Object System.Net.WebClient
        $startTime = Get-Date
        $lastUpdateTime = $startTime
        
        # Set global variables for use in event handlers
        $global:startTime = $startTime
        $global:lastUpdateTime = $lastUpdateTime
        
        # Create event handlers for download progress
        $downloadProgressEvent = Register-ObjectEvent -InputObject $webClient -EventName DownloadProgressChanged -Action {
            $bytesReceived = $EventArgs.BytesReceived
            $totalBytes = $EventArgs.TotalBytesToReceive
            $progressPercentage = $EventArgs.ProgressPercentage
            $currentTime = Get-Date
            
            # Only update display every 500ms to avoid console flicker
            if (($currentTime - $global:lastUpdateTime).TotalMilliseconds -ge 500) {
                $global:lastUpdateTime = $currentTime
                
                $elapsedTime = $currentTime - $global:startTime
                $elapsedSeconds = [math]::Floor($elapsedTime.TotalSeconds)
                
                $downloadSpeed = if ($elapsedSeconds -gt 0) { $bytesReceived / $elapsedSeconds } else { 0 }
                $downloadSpeedMbps = [math]::Round($downloadSpeed / 1024 / 1024 * 8, 2)
                
                $remainingBytes = $totalBytes - $bytesReceived
                $estimatedTimeRemaining = if ($downloadSpeed -gt 0) { [TimeSpan]::FromSeconds([math]::Floor($remainingBytes / $downloadSpeed)) } else { [TimeSpan]::Zero }
                
                # Format sizes for display
                $bytesSoFar = if ($bytesReceived -ge 1GB) {
                    "{0:N2} GB" -f ($bytesReceived / 1GB)
                } elseif ($bytesReceived -ge 1MB) {
                    "{0:N2} MB" -f ($bytesReceived / 1MB)
                } elseif ($bytesReceived -ge 1KB) {
                    "{0:N2} KB" -f ($bytesReceived / 1KB)
                } else {
                    "$bytesReceived B"
                }
                
                $totalSize = if ($totalBytes -ge 1GB) {
                    "{0:N2} GB" -f ($totalBytes / 1GB)
                } elseif ($totalBytes -ge 1MB) {
                    "{0:N2} MB" -f ($totalBytes / 1MB)
                } elseif ($totalBytes -ge 1KB) {
                    "{0:N2} KB" -f ($totalBytes / 1KB)
                } else {
                    "$totalBytes B"
                }
                
                $estimatedTime = if ($estimatedTimeRemaining.TotalHours -ge 1) {
                    "{0:D2}:{1:D2}:{2:D2}" -f $estimatedTimeRemaining.Hours, $estimatedTimeRemaining.Minutes, $estimatedTimeRemaining.Seconds
                } else {
                    "{0:D2}:{1:D2}" -f $estimatedTimeRemaining.Minutes, $estimatedTimeRemaining.Seconds
                }
                
                $elapsedTimeStr = if ($elapsedTime.TotalHours -ge 1) {
                    "{0:D2}:{1:D2}:{2:D2}" -f $elapsedTime.Hours, $elapsedTime.Minutes, $elapsedTime.Seconds
                } else {
                    "{0:D2}:{1:D2}" -f $elapsedTime.Minutes, $elapsedTime.Seconds
                }
                
                # Clear the console and rewrite the progress information
                Clear-Host
                Write-Host "Downloading: $gameName ($gameId)" -ForegroundColor Green
                Write-Host "Progress: $progressPercentage%" -ForegroundColor Cyan
                Write-Host "Downloaded: $bytesSoFar of $totalSize" -ForegroundColor Yellow
                Write-Host "Speed: $downloadSpeedMbps Mbps" -ForegroundColor Yellow
                Write-Host "Time Elapsed: $elapsedTimeStr" -ForegroundColor Yellow
                Write-Host "Estimated Time Remaining: $estimatedTime" -ForegroundColor Yellow
                Write-Host "`nPress Ctrl+C to cancel the download" -ForegroundColor Red
            }
        }
        
        $downloadCompletedEvent = Register-ObjectEvent -InputObject $webClient -EventName DownloadFileCompleted -Action {
            # Clear console and show extraction message
            Clear-Host
            Write-Host "Download completed!" -ForegroundColor Green
            Write-Host "Starting extraction process..." -ForegroundColor Yellow
            
            try {
                # Define the self-contained extraction function
                function Start-GameExtraction {
                    # Load settings independently (similar to ass.ps1 but with adjusted path)
                    $scriptPath = $settingsFolder
                    $settingsPath = Join-Path -Path $scriptPath -ChildPath "settings.json"
                    
                    Write-Host "Loading settings from: $settingsPath" -ForegroundColor Gray
                    
                    # Check if settings file exists
                    if (-not (Test-Path -Path $settingsPath)) {
                        Write-Host "Error: Settings file not found at '$settingsPath'." -ForegroundColor Red
                        return
                    }
                    
                    # Load and parse the settings.json file
                    $extractSettings = Get-Content -Path $settingsPath -ErrorAction Stop | ConvertFrom-Json
                    
                    # Get paths from settings
                    $tempDownloadPath = $extractSettings.TempDownloadPath
                    $downloadPath = $extractSettings.DownloadPath
                    
                    Write-Host "Loaded TempDownloadPath: $tempDownloadPath" -ForegroundColor Gray
                    Write-Host "Loaded DownloadPath: $downloadPath" -ForegroundColor Gray
                    
                    # Verify paths exist
                    if (-not (Test-Path -Path $tempDownloadPath)) {
                        Write-Host "Error: TempDownloadPath '$tempDownloadPath' does not exist." -ForegroundColor Red
                        return
                    }
                    
                    if (-not (Test-Path -Path $downloadPath)) {
                        Write-Host "Error: DownloadPath '$downloadPath' does not exist." -ForegroundColor Red
                        return
                    }
                    
                    # Check if 7-Zip is installed
                    $7zipPath = "C:\Program Files\7-Zip\7z.exe"
                    if (-not (Test-Path -Path $7zipPath)) {
                        # Try alternative paths
                        $alternativePaths = @(
                            "${env:ProgramFiles(x86)}\7-Zip\7z.exe",
                            ".\7zip\7z.exe"
                        )
                        
                        $found = $false
                        foreach ($path in $alternativePaths) {
                            if (Test-Path -Path $path) {
                                $7zipPath = $path
                                $found = $true
                                break
                            }
                        }
                        
                        if (-not $found) {
                            Write-Host "Error: 7-Zip is not installed at any expected location." -ForegroundColor Red
                            Write-Host "Please install 7-Zip or ensure it's in one of these locations:" -ForegroundColor Yellow
                            Write-Host "  - C:\Program Files\7-Zip\7z.exe" -ForegroundColor Yellow
                            Write-Host "  - C:\Program Files (x86)\7-Zip\7z.exe" -ForegroundColor Yellow
                            Write-Host "  - .\7zip\7z.exe" -ForegroundColor Yellow
                            return
                        }
                    }
                    
                    # Get all .7z files in the temp download path
                    Write-Host "Searching for .7z files in: $tempDownloadPath" -ForegroundColor Cyan
                    $7zFiles = Get-ChildItem -Path $tempDownloadPath -Filter "*.7z"
                    
                    # If no .7z files found, exit
                    if ($7zFiles.Count -eq 0) {
                        Write-Host "No .7z files found in '$tempDownloadPath'." -ForegroundColor Yellow
                        return
                    }
                    
                    Write-Host "Found $($7zFiles.Count) .7z files to process." -ForegroundColor Green
                    
                    # Process each .7z file
                    foreach ($file in $7zFiles) {
                        $filePath = $file.FullName
                        
                        # Extract the file
                        Write-Host "Extracting: $filePath to $downloadPath" -ForegroundColor Cyan
                        & "$7zipPath" x "$filePath" -o"$downloadPath" -y
                        
                        # Check if extraction was successful
                        if ($LASTEXITCODE -eq 0) {
                            # Delete the original .7z file
                            Write-Host "Extraction successful. Deleting original file: $filePath" -ForegroundColor Green
                            Remove-Item -Path $filePath -Force
                        } else {
                            Write-Host "Failed to extract: $filePath. Skipping deletion." -ForegroundColor Red
                        }
                    }
                    
                    Write-Host "All .7z files have been processed." -ForegroundColor Green
                    Write-Host "Go to $downloadPath to play the game." -ForegroundColor Cyan
                }
                
                # Call the extraction function
                Start-GameExtraction
            }
            catch {
                Write-Host "An error occurred during extraction: $($_.Exception.Message)" -ForegroundColor Red
                Write-Host "Error details: $($_.Exception.StackTrace)" -ForegroundColor Red
            }
        }
        
        # Start the download
        try {
            $webClient.DownloadFileAsync([Uri]$downloadUrl, $downloadPath)
            
            # Wait for download to complete
            while ($webClient.IsBusy) {
                Start-Sleep -Milliseconds 100
            }
        }
        catch {
            Write-Host "An error occurred during download: $($_.Exception.Message)" -ForegroundColor Red
        }
        finally {
            # Clean up event handlers
            if ($downloadProgressEvent) { Unregister-Event -SourceIdentifier $downloadProgressEvent.Name }
            if ($downloadCompletedEvent) { Unregister-Event -SourceIdentifier $downloadCompletedEvent.Name }
            $webClient.Dispose()
        }
    }
    catch {
        Write-Host "An error occurred: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# Main CLI interface
function Start-MainInterface($username) {
    Clear-Host
    Write-Host "Welcome to CCLS Games CLI Tool, $username!" -ForegroundColor Green
    
    # Load settings to check setup status
    $settings = Initialize-Settings
    
    # Show appropriate message based on setup status
    if ($settings.HasCompletedSetup) {
        Write-Host "Type 'help' for a list of available commands.`n" -ForegroundColor Cyan
    }
    else {
        Write-Host "ALERT, type command 'setup' to set critical values before downloading." -ForegroundColor Red
    }
    
    $running = $true
    while ($running) {
        Write-Host "CCLS>" -ForegroundColor Yellow -NoNewline
        $command = Read-Host
        
        switch -Regex ($command.ToLower()) {
            "^exit|^quit" {
                $running = $false
                Write-Host "Thank you for using the CCLS Games CLI Tool. Goodbye!" -ForegroundColor Cyan
            }
            "^help" {
                Write-Host "`nAvailable Commands:" -ForegroundColor Green
                Write-Host "  help         - Show this help message"
                Write-Host "  setup        - Configure download directories"
                Write-Host "  search       - Search for game information by CG number"
                Write-Host "  get          - Download and install a game by CG number"
                Write-Host "  exit, quit   - Exit the application"
                Write-Host "  logout       - Log out and exit"
                Write-Host "  forget       - Remove stored credentials"
                Write-Host ""
            }
            "^setup" {
                Start-Setup
            }
            "^search$" {
                Clear-Host
                Write-Host "To use the search command please provide a valid CG number in this format 'search cg0000'" -ForegroundColor Cyan
                Write-Host "To get the CG number of a game, go to the main games page and click on any game, then check" -ForegroundColor Cyan
                Write-Host "the URL 'https://games.ccls.icu/game.php?id=cg0000' and the 'cg0000' part in URL is the CG number" -ForegroundColor Cyan
            }
            "^search\s+(cg\d{4})$" {
                $cgNumber = $matches[1]
                Search-Game -cgNumber $cgNumber
            }
            "^get$" {
                Clear-Host
                Write-Host "To use the get command please provide a valid CG number in this format 'get cg0000'" -ForegroundColor Cyan
                Write-Host "To get the CG number of a game, go to the main games page and click on any game, then check" -ForegroundColor Cyan
                Write-Host "the URL 'https://games.ccls.icu/game.php?id=cg0000' and the 'cg0000' part in URL is the CG number." -ForegroundColor Cyan
                Write-Host "ALERT, the get command will start the downloading proccess of the game specified, to stop it do 'Ctrl C'" -ForegroundColor Red
            }
            "^get\s+(cg\d{4})$" {
                $cgNumber = $matches[1]
                Get-Game -cgNumber $cgNumber
            }
            "^logout" {
                $running = $false
                Write-Host "Logging out..." -ForegroundColor Cyan
                # Clear the current session but keep credentials if they exist
            }
            "^forget" {
                if (Test-Path $credentialsFile) {
                    Remove-Item -Path $credentialsFile -Force
                    $settings = Initialize-Settings
                    $settings.RememberLogin = $false
                    Save-Settings -settings $settings
                    Write-Host "Stored credentials have been removed." -ForegroundColor Green
                }
                else {
                    Write-Host "No stored credentials found." -ForegroundColor Yellow
                }
            }
            default {
                Write-Host "Unknown command. Type 'help' for a list of available commands." -ForegroundColor Red
            }
        }
    }
}

# Main application flow
function Start-CclsCliTool {
    Clear-Host
    Write-Host "Hello and welcome to the CCLS Games CLI Tool" -ForegroundColor Green
    Write-Host "Before proceeding to using this software you will need to sign in."
    Write-Host "If you do not have an account already please go to $baseUrl/login.php?signup to register a new account.`n" -ForegroundColor Cyan
    
    $settings = Initialize-Settings
    
    # Try auto-login if remember login is enabled
    $loginResult = @{ Success = $false }
    if ($settings.RememberLogin) {
        $loginResult = Start-AutoLogin
    }
    
    # If auto-login failed or is disabled, do manual login
    if (-not $loginResult.Success) {
        $loginResult = Start-ManualLogin
    }
    
    # If login succeeded, show main interface
    if ($loginResult.Success) {
        Start-MainInterface -username $loginResult.Username
    }
    else {
        Write-Host "Login failed. Press any key to exit..." -ForegroundColor Red
        $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

# Start the application
Start-CclsCliTool