param(
    [int]$Port = 7865
)

$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $MyInvocation.MyCommand.Path
$VenvPython = Join-Path $Root ".venv\Scripts\python.exe"

[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
$OutputEncoding = [System.Text.UTF8Encoding]::new()
$env:PYTHONIOENCODING = "utf-8"
$env:PYTHONUTF8 = "1"
$env:COPITA_STARTUP_LOG = "1"
$env:XFORMERS_FORCE_DISABLE_TRITON = "1"

function Write-CopitaStep([string]$Message) {
    Write-Host ("[{0}] {1}" -f (Get-Date -Format "HH:mm:ss"), $Message)
}

Write-Host ""
Write-Host "====================================="
Write-Host " Copita"
Write-Host "====================================="
Write-Host ""

Write-CopitaStep "Checking Python environment..."
if (!(Test-Path $VenvPython)) {
    Write-Host "Python environment is missing."
    Write-Host "Run setup_first_time.bat first."
    exit 1
}

$env:STYLE_DIFF_PORT = "$Port"
Write-CopitaStep "Starting Copita..."
Write-CopitaStep "First launch or large model folders may take a little while."
Write-CopitaStep "If the log is moving, the app is preparing normally."
Write-Host "Opening http://127.0.0.1:$Port"
Write-Host ""
& $VenvPython (Join-Path $Root "app.py")
