# =============================================================
# (주)지오정보기술 홈페이지 스타트업 스크립트 — Windows
# =============================================================
# 사용법: .\start.ps1 [dev|prod|build]
# =============================================================

param([string]$Mode = "dev")

$ErrorActionPreference = "Stop"
$ScriptDir   = Split-Path -Parent $MyInvocation.MyCommand.Path
$BackendDir  = "$ScriptDir\backend"
$FrontendDir = "$ScriptDir\frontend"

function Write-OK   { param($msg) Write-Host "[OK]  $msg" -ForegroundColor Green }
function Write-Warn { param($msg) Write-Host "[WARN] $msg" -ForegroundColor Yellow }
function Write-Fail { param($msg) Write-Host "[FAIL] $msg" -ForegroundColor Red; exit 1 }
function Write-Info { param($msg) Write-Host "      $msg" }

Write-Host "=================================================="
Write-Host "  (주)지오정보기술 홈페이지 시작 — Windows"
Write-Host "  모드: $Mode"
Write-Host "=================================================="

# ── 1. Java 확인 ──────────────────────────────────────────────
if (-not (Get-Command java -ErrorAction SilentlyContinue)) {
    Write-Fail "Java가 설치되지 않았습니다. setup_windows.ps1을 먼저 실행하세요."
}
$javaVer = & java -version 2>&1 | Select-Object -First 1
Write-OK "Java 감지: $javaVer"

# ── 2. Maven 감지 및 설치 ────────────────────────────────────
function Get-MavenCommand {
    # mvnw.cmd (Wrapper) 우선 확인
    $mvnw = "$BackendDir\mvnw.cmd"
    if (Test-Path $mvnw) {
        Write-OK "Maven Wrapper(mvnw.cmd) 사용 — 별도 Maven 설치 불필요"
        return $mvnw
    }

    # 시스템 Maven 확인
    $mvnCmd = Get-Command mvn -ErrorAction SilentlyContinue
    if ($mvnCmd) {
        $ver = & mvn --version 2>&1 | Select-Object -First 1
        Write-OK "시스템 Maven 감지: $ver"
        return "mvn"
    }

    # Maven 없음 → 자동 설치
    Write-Warn "Maven이 설치되지 않았습니다. 자동 설치를 진행합니다..."
    Install-Maven
    return "mvn"
}

function Install-Maven {
    # Chocolatey로 설치 시도
    if (Get-Command choco -ErrorAction SilentlyContinue) {
        Write-Info "Chocolatey로 Maven 설치 중..."
        choco install maven -y --no-progress 2>&1 | Out-Null
        $mp = [System.Environment]::GetEnvironmentVariable("Path", "Machine")
        $up = [System.Environment]::GetEnvironmentVariable("Path", "User")
        $env:Path = "$mp;$up"
        if (Get-Command mvn -ErrorAction SilentlyContinue) {
            Write-OK "Maven 설치 완료 (Chocolatey)"
            return
        }
    }

    # 수동 설치
    $MavenVer    = if ($env:MAVEN_VER) { $env:MAVEN_VER } else { "3.9.6" }
    $MavenUrl    = "https://archive.apache.org/dist/maven/maven-3/$MavenVer/binaries/apache-maven-$MavenVer-bin.zip"
    $MavenHome   = "C:\tools\maven"

    Write-Info "Maven $MavenVer 수동 설치 중..."
    try {
        Invoke-WebRequest $MavenUrl -OutFile "$env:TEMP\maven.zip" -UseBasicParsing -TimeoutSec 120
        Expand-Archive "$env:TEMP\maven.zip" -DestinationPath "C:\tools" -Force
        if (Test-Path "C:\tools\apache-maven-$MavenVer") {
            if (Test-Path $MavenHome) { Remove-Item $MavenHome -Recurse -Force }
            Rename-Item "C:\tools\apache-maven-$MavenVer" $MavenHome
        }
        [System.Environment]::SetEnvironmentVariable("MAVEN_HOME", $MavenHome, "Machine")
        $currentPath = [System.Environment]::GetEnvironmentVariable("Path", "Machine")
        [System.Environment]::SetEnvironmentVariable("Path", "$currentPath;$MavenHome\bin", "Machine")
        $env:MAVEN_HOME = $MavenHome
        $env:Path       = "$env:Path;$MavenHome\bin"
        Write-OK "Maven $MavenVer 수동 설치 완료: $MavenHome"
    } catch {
        Write-Fail "Maven 설치 실패: $_ — 수동으로 https://maven.apache.org/download.cgi 에서 설치하세요."
    }
}

$MvnCmd = Get-MavenCommand

# ── 3. Node.js/npm 확인 ──────────────────────────────────────
$HasNpm = $false
if (Get-Command npm -ErrorAction SilentlyContinue) {
    $npmVer = npm --version
    Write-OK "npm $npmVer 감지"
    $HasNpm = $true
} else {
    Write-Warn "npm 없음 — 프론트엔드는 빌드 없이 실행됩니다."
}

# ── 4. 실행 ───────────────────────────────────────────────────
switch ($Mode) {

    "dev" {
        Write-Host ""
        Write-Info "=== 개발 모드 시작 ==="
        Write-Info "백엔드: http://localhost:8080"
        if ($HasNpm) { Write-Info "프론트: http://localhost:3000" }

        # 프론트엔드 의존성 설치
        if ($HasNpm -and -not (Test-Path "$FrontendDir\node_modules")) {
            Push-Location $FrontendDir
            npm install
            Pop-Location
        }

        # 백엔드 시작
        New-Item -ItemType Directory -Force "$BackendDir\data" | Out-Null
        Push-Location $BackendDir
        $springJob = Start-Job -ScriptBlock { param($dir,$mvn) cd $dir; & $mvn spring-boot:run } -ArgumentList $BackendDir, $MvnCmd
        Pop-Location

        # 프론트엔드 시작 (npm 있을 때)
        if ($HasNpm) {
            Push-Location $FrontendDir
            Start-Process npm -ArgumentList "run dev" -NoNewWindow
            Pop-Location
        }

        Write-OK "서비스 시작 완료"
        Write-Host "종료: Ctrl+C"
        Wait-Job $springJob
    }

    "prod" {
        Write-Host ""
        Write-Info "=== 운영 모드 ==="
        if ($HasNpm) {
            Push-Location $FrontendDir
            if (-not (Test-Path "node_modules")) { npm install }
            npm run build
            Write-OK "React 빌드 완료"
            Pop-Location
        }
        New-Item -ItemType Directory -Force "$BackendDir\data" | Out-Null
        Push-Location $BackendDir
        & $MvnCmd clean package "-DskipTests" -q
        $jar = Get-ChildItem target -Filter "*.jar" | Where-Object { $_.Name -notmatch "sources" } | Select-Object -First 1
        Write-OK "패키징 완료: $($jar.Name)"
        java -jar $jar.FullName
        Pop-Location
    }

    "build" {
        if ($HasNpm) {
            Push-Location $FrontendDir
            if (-not (Test-Path "node_modules")) { npm install }
            npm run build
            Write-OK "React 빌드 완료"
            Pop-Location
        }
        Push-Location $BackendDir
        & $MvnCmd clean package "-DskipTests" -q
        $jar = Get-ChildItem target -Filter "*.jar" | Where-Object { $_.Name -notmatch "sources" } | Select-Object -First 1
        Write-OK "빌드 완료: $BackendDir\$($jar.Name)"
        Write-Info "실행: java -jar $BackendDir\target\$($jar.Name)"
        Pop-Location
    }

    default {
        Write-Host "사용법: .\start.ps1 [dev|prod|build]"
        exit 1
    }
}
