# RPG Workshop Setup Script for Windows (PowerShell)
# This script sets up the conda environment and installs dependencies
#
# ============================================================================
# TERMS OF SERVICE NOTICE
# ============================================================================
# By running this script, you agree to the Anaconda Terms of Service:
# https://www.anaconda.com/terms-of-service
#
# This script will prompt you to accept the Anaconda TOS before proceeding.
# If you do not agree, please exit now (Ctrl+C).
# ============================================================================

$ErrorActionPreference = "Stop"

# Get the directory where this script is located
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectRoot = Split-Path -Parent $ScriptDir

Write-Host "=== RPG Workshop Setup ===" -ForegroundColor Cyan
Write-Host ""

$ReqFile = "$ProjectRoot\requirements.txt"
if (-not (Test-Path $ReqFile)) {
    Write-Host "Error: Missing requirements.txt at: $ReqFile" -ForegroundColor Red
    exit 1
}

# Function to check if conda is available
function Test-CondaInstalled {
    try {
        $cmd = Get-Command conda -CommandType Application -ErrorAction Stop
        & $cmd.Source --version *> $null
        return ($LASTEXITCODE -eq 0)
    }
    catch {
        # Check common installation paths
        $condaPaths = @(
            "$env:USERPROFILE\miniconda3\Scripts\conda.exe",
            "$env:USERPROFILE\anaconda3\Scripts\conda.exe",
            "C:\ProgramData\miniconda3\Scripts\conda.exe",
            "C:\ProgramData\anaconda3\Scripts\conda.exe"
        )

        foreach ($path in $condaPaths) {
            if (Test-Path $path) {
                $condaDir = Split-Path -Parent $path
                $env:PATH = "$condaDir;$env:PATH"
                return $true
            }
        }

        return $false
    }
}

# Function to verify SHA256 hash
function Test-Sha256 {
    param (
        [string]$FilePath,
        [string]$ExpectedHash
    )

    $actualHash = (Get-FileHash -Path $FilePath -Algorithm SHA256).Hash.ToLower()
    if ($actualHash -ne $ExpectedHash.ToLower()) {
        Write-Host "Error: SHA-256 mismatch for $FilePath" -ForegroundColor Red
        Write-Host "Expected: $ExpectedHash" -ForegroundColor Red
        Write-Host "Actual:   $actualHash" -ForegroundColor Red
        Write-Host "Deleting corrupted file." -ForegroundColor Red
        Remove-Item $FilePath -Force
        return $false
    }
    Write-Host "Checksum verified for $FilePath" -ForegroundColor Green
    return $true
}

# Function to install Miniconda
function Install-Miniconda {
    Write-Host "Conda not found. Installing Miniconda..." -ForegroundColor Yellow

    $installerUrl = "https://repo.anaconda.com/miniconda/Miniconda3-py313_25.7.0-2-Windows-x86_64.exe"
    $expectedHash = "0505a3d4a7dab58ca621208e89efede4b6b8d817858b60d6eccc9303f2f3ebb0"
    $installerPath = "$env:TEMP\miniconda_installer.exe"
    $installDir = "$env:USERPROFILE\miniconda3"

    Write-Host "Downloading Miniconda from $installerUrl..."

    try {
        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
        Invoke-WebRequest -Uri $installerUrl -OutFile $installerPath -UseBasicParsing
    }
    catch {
        Write-Host "Error downloading Miniconda: $_" -ForegroundColor Red
        exit 1
    }

    if (-not (Test-Sha256 -FilePath $installerPath -ExpectedHash $expectedHash)) {
        exit 1
    }

    Write-Host "Installing Miniconda to: $installDir"
    Write-Host "Installing Miniconda (this may take a few minutes)..."

    # Run silent install
    $installArgs = "/S /InstallationType=JustMe /RegisterPython=0 /AddToPath=1 /D=$installDir"
    Start-Process -FilePath $installerPath -ArgumentList $installArgs -Wait -NoNewWindow

    # Clean up installer
    Remove-Item $installerPath -Force

    # Add conda to PATH for this session
    $env:PATH = "$installDir\Scripts;$installDir;$env:PATH"

    # Initialize conda for PowerShell
    Write-Host "Initializing conda for PowerShell..."
    & "$installDir\Scripts\conda.exe" init powershell

    Write-Host "Miniconda installed successfully!" -ForegroundColor Green
    Write-Host ""
}

# Function to initialize conda for this session
function Initialize-CondaSession {
    # Find conda installation
    $condaExe = (Get-Command conda -All -ErrorAction Stop |
    Where-Object { $_.CommandType -in 'Application','ExternalScript' -and $_.Path } |
    Select-Object -First 1
    ).Path
    if ($condaExe) {
        $condaDir = Split-Path -Parent (Split-Path -Parent $condaExe)
    }
    else {
        $condaDir = "$env:USERPROFILE\miniconda3"
    }

    # Source the conda hook script
    $condaHook = "$condaDir\shell\condabin\conda-hook.ps1"
    if (Test-Path $condaHook) {
        . $condaHook
    }
}



# Function to accept Anaconda TOS
function Accept-CondaTos {
    Write-Host "This script will accept Anaconda's Terms of Service on your behalf." -ForegroundColor Yellow
    Write-Host "Review the TOS at: https://www.anaconda.com/terms-of-service" -ForegroundColor Yellow
    Write-Host ""

    Write-Host "Installing conda-anaconda-tos (if needed)..." -ForegroundColor Yellow
    $tosList = & conda list -n base conda-anaconda-tos 2>$null
    if (-not ($tosList -match "conda-anaconda-tos")) {
        & conda install -n base -y conda-anaconda-tos
    }

    Write-Host "Accepting Anaconda Terms of Service..." -ForegroundColor Yellow
    & conda tos accept
    Write-Host "TOS accepted." -ForegroundColor Green
    Write-Host ""
}

# Function to set base environment auto-activation preference
function Set-BaseDefault {
    $confirmation = Read-Host "Do you want base to be activated for new terminals by default? (Y/N)"
    if ($confirmation -eq 'Y' -or $confirmation -eq 'y') {
        & conda config --set auto_activate true
        Write-Host ""
        Write-Host "Setting base to be activated for new terminals by default..."
        Write-Host "If you changed your mind, you can run 'conda config --set auto_activate false' later."
        Write-Host "The command 'conda deactivate' can be used to exit the base environment."
    }
    else {
        & conda config --set auto_activate false
        Write-Host ""
        Write-Host "If you changed your mind, you can run 'conda config --set auto_activate true' later."
        Write-Host "The command 'conda deactivate' can be used to exit the base environment."
    }
}

# Main script
Write-Host "Checking for conda installation..."
$NewCondaInstall = $false

if (-not (Test-CondaInstalled)) {
    Write-Host "Conda is not installed." -ForegroundColor Yellow
    Install-Miniconda
    $NewCondaInstall = $true
}

# Refresh environment and get conda version
$condaVersion = & conda --version
Write-Host "Conda found: $condaVersion" -ForegroundColor Green
Write-Host ""

# === ACCEPTS ANACONDA TERMS OF SERVICE ===
# The following section accepts Anaconda's Terms of Service for this user.
# This is required for non-interactive conda operations.
# TOS: https://www.anaconda.com/terms-of-service
Accept-CondaTos

# Setup if conda base should run for new terminals by default
Set-BaseDefault

# Initialize conda for this session
Initialize-CondaSession

# Check if environment already exists
$envName = "RPG_Workshop1"
$envList = & conda env list

if ($envList -match "^$envName\s") {
    Write-Host "Environment '$envName' already exists." -ForegroundColor Yellow
}
else {
    Write-Host "Creating conda environment '$envName' with Python 3.12..."
    & conda create -n $envName python=3.12 -y
    Write-Host "Environment created successfully!" -ForegroundColor Green
}

Write-Host ""
Write-Host "Running environment '$envName'..." -ForegroundColor Cyan
Write-Host ""
Write-Host "Installing requirements from requirements.txt..."
& conda run -n $envName python -m pip install -r "$ProjectRoot\requirements.txt"

Write-Host ""
Write-Host "=== Setup Complete! ===" -ForegroundColor Cyan
Write-Host ""
Write-Host "Environment '$envName' is ready."
Write-Host "To activate this environment in the future, run:"
Write-Host "    conda activate $envName" -ForegroundColor Yellow
Write-Host ""
