param(
    [switch]$RemoveLockfile,
    [switch]$Force
)

$commonScript = Join-Path $PSScriptRoot "script-common.ps1"
if (-not (Test-Path $commonScript)) {
    throw "Missing helper script: $commonScript"
}
. $commonScript

$repoRoot = Resolve-JournalRepoRoot -StartPath $PSScriptRoot
$appRoot = Resolve-JournalAppRoot -RepoRoot $repoRoot

Write-Host "Cleaning npm artifacts for Journal.App" -ForegroundColor Cyan
Write-Host "Using app root: $appRoot" -ForegroundColor DarkGray

$processNames = @("node", "journalapp", "tauri")
Get-Process -ErrorAction SilentlyContinue |
    Where-Object { $processNames -contains $_.ProcessName } |
    ForEach-Object {
        try {
            Stop-Process -Id $_.Id -Force -ErrorAction Stop
            Write-Host "Stopped process: $($_.ProcessName) ($($_.Id))" -ForegroundColor DarkGray
        }
        catch {
            Write-Warning "Failed to stop process $($_.ProcessName) ($($_.Id)): $($_.Exception.Message)"
        }
    }

Push-Location $appRoot
try {
    $nodeModulesPath = Join-Path $appRoot "node_modules"
    $lockfilePath = Join-Path $appRoot "package-lock.json"

    if (Test-Path $nodeModulesPath) {
        if (-not $Force) {
            Write-Host "Removing node_modules (use -Force to suppress prompt)..." -ForegroundColor Yellow
        }
        Remove-Item -Recurse -Force $nodeModulesPath
        Write-Host "Removed node_modules." -ForegroundColor Green
    }
    else {
        Write-Host "node_modules not found; nothing to remove." -ForegroundColor DarkGray
    }

    if ($RemoveLockfile) {
        if (Test-Path $lockfilePath) {
            Remove-Item -Force $lockfilePath
            Write-Host "Removed package-lock.json." -ForegroundColor Green
        }
        else {
            Write-Host "package-lock.json not found; nothing to remove." -ForegroundColor DarkGray
        }
    }
    else {
        Write-Host "Keeping package-lock.json (pass -RemoveLockfile to delete)." -ForegroundColor DarkGray
    }
}
finally {
    Pop-Location
}
