# Set console encoding to UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
[System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# Set error action preference
$ErrorActionPreference = "Stop"

# Define color output function
function Write-ColorOutput($ForegroundColor) {
    $fc = $host.UI.RawUI.ForegroundColor
    $host.UI.RawUI.ForegroundColor = $ForegroundColor
    if ($args) {
        Write-Output $args
    }
    $host.UI.RawUI.ForegroundColor = $fc
}

# Create necessary directories
Write-ColorOutput Green "Creating necessary directories..."
$directories = @("config", "data", "uploads")
foreach ($dir in $directories) {
    if (-not (Test-Path $dir)) {
        New-Item -ItemType Directory -Path $dir | Out-Null
        Write-ColorOutput Yellow "Created directory: $dir"
    }
}

# Check if config file exists
$configPath = "config/config.yaml"
if (-not (Test-Path $configPath)) {
    Write-ColorOutput Green "Creating default configuration file..."
    $configContent = @"
server:
  port: 8081
  mode: debug

database:
  type: sqlite3
  path: ./data/license.db

jwt:
  secret: your-secret-key-change-this
  expire: 24h

email:
  host: smtp.example.com
  port: 587
  username: your-email@example.com
  password: your-password

upload:
  path: ./uploads

site:
  title: "授权验证管理平台"
  description: "专业的软件授权和设备管理平台"
  base_url: "http://localhost:8080"
  icp: "京ICP备XXXXXXXX号-1"
  copyright: "© 2024 Your Company Name. All rights reserved."
  logo: "/static/images/logo.png"
  favicon: "/static/images/favicon.ico"
"@
    $configContent | Out-File -FilePath $configPath -Encoding UTF8
    Write-ColorOutput Yellow "Created default config file: $configPath"
}

# Compile program
Write-ColorOutput Green "Compiling program..."
try {
    go env -w GOPROXY=https://goproxy.cn,direct
    go mod tidy
    go build -o licserver.exe cmd/main.go
    if ($LASTEXITCODE -ne 0) {
        throw "Compilation failed"
    }
    Write-ColorOutput Yellow "Compilation successful"
}
catch {
    Write-ColorOutput Red "Compilation failed: $_"
    exit 1
}

# Start server
Write-ColorOutput Green "Starting server..."
try {
    # Check if port is in use
    $port = 8081
    $portInUse = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue
    if ($portInUse) {
        throw "Port $port is already in use"
    }

    # Start server
    .\licserver.exe

    # Capture Ctrl+C
    $handler = {
        Write-ColorOutput Yellow "`nShutting down server..."
        Stop-Process -Name "licserver" -Force -ErrorAction SilentlyContinue
    }
    $null = Register-ObjectEvent -InputObject ([Console]) -EventName CancelKeyPress -Action $handler
}
catch {
    Write-ColorOutput Red "Startup failed: $_"
    exit 1
}

# 检查并下载 echarts
$echartsPath = "web/static/lib/echarts.min.js"
if (-not (Test-Path $echartsPath)) {
    Write-ColorOutput Green "Downloading echarts..."
    $echartsUrl = "https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"
    
    try {
        Invoke-WebRequest -Uri $echartsUrl -OutFile $echartsPath
        Write-ColorOutput Yellow "Downloaded echarts successfully"
    }
    catch {
        Write-ColorOutput Red "Failed to download echarts: $_"
        exit 1
    }
} 