#!/usr/bin/env pwsh
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if (-not (Test-Path -Path ".\evibes" -PathType Container))
{
    Write-Host "❌  Please run this script from the project's root (where the 'evibes' directory lives)." -ForegroundColor Red
    exit 1
}

$purple = "`e[38;2;121;101;209m"
$reset = "`e[0m"

$artPath = Join-Path (Split-Path -Parent $MyInvocation.MyCommand.Definition) '..\ASCII_ART_EVIBES'
if (-not (Test-Path $artPath))
{
    Write-Host "❌  Could not find ASCII art at $artPath" -ForegroundColor Red
    exit 1
}

$art = Get-Content -Raw -Path $artPath
$art -split "`r?`n" | ForEach-Object {
    Write-Host "$purple$_$reset"
}

Write-Host "`n                                                                       by WISELESS TEAM`n" -ForegroundColor Gray

if (-not (Test-Path '.env'))
{
    Write-Warning ".env file not found. Exiting without running Docker steps."
    exit 0
}

$cpuCount = [Environment]::ProcessorCount
if ($cpuCount -lt 4)
{
    Write-Error "Insufficient CPU cores: $cpuCount detected. Minimum 4 required."
    exit 1
}

$totalMemBytes = (Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory
$totalMemGB = [Math]::Round($totalMemBytes / 1GB, 2)
if ($totalMemGB -lt 6)
{
    Write-Error "Insufficient RAM: $totalMemGB GB detected. Minimum 6 GB required."
    exit 1
}

$currentDrive = Split-Path -Qualifier $PWD
$driveLetter = $currentDrive.Substring(0, 1)
$driveInfo = Get-PSDrive -Name $driveLetter
$freeGB = [Math]::Round($driveInfo.Free / 1GB, 2)
if ($freeGB -lt 20)
{
    Write-Error "Insufficient free disk space on drive $driveLetter`: $freeGB GB available. Minimum 20 GB required."
    exit 1
}

Write-Host "System requirements met: CPU cores=$cpuCount, RAM=${totalMemGB}GB, FreeDisk=${freeGB}GB" -ForegroundColor Green

$Spinner = @('|', '/', '-', '\')
$Colors = @('White', 'Gray')
$Delay = 100

function Invoke-Spinner
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$Arguments,
        [Parameter(Mandatory)][string]$Message
    )
    Write-Host -NoNewLine -ForegroundColor Cyan ("{0}… " -f $Message)
    $si = New-Object System.Diagnostics.ProcessStartInfo
    $si.FileName = "docker"
    $si.Arguments = "$Arguments --ansi never"
    $si.RedirectStandardOutput = $true
    $si.RedirectStandardError = $true
    $si.UseShellExecute = $false
    $p = [System.Diagnostics.Process]::Start($si)
    $i = 0
    while (-not $p.HasExited)
    {
        $frame = $Spinner[$i % $Spinner.Length]
        $col = $Colors[$i % $Colors.Length]
        Write-Host -NoNewLine -ForegroundColor $col $frame
        Start-Sleep -Milliseconds $Delay
        Write-Host -NoNewline "`b"
        $i++
    }
    $p.WaitForExit()
    Write-Host -ForegroundColor Green "✔"
}

Invoke-Spinner -Arguments "compose pull" -Message "Pulling related images"
Invoke-Spinner -Arguments "compose build" -Message "Building the project's images"
