param(
    [string]$IncludesFile = ".includes",
    [string]$Destination  = "C:\Users\matthes01\Documents\lst\lstV2",
    [string]$BaseDir      = "C:\Users\matthes01\Documents\lst"
)

# .\copy-includes.ps1 will run with defaults
# .\copy-includes.ps1 -IncludesFile ".\mylist.txt" -Destination "D:\build\lstV2" will override defaults

if (-Not (Test-Path $IncludesFile)) {
    Write-Error "Includes file not found: $IncludesFile"
    exit 1
}

# Ensure destination exists
if (!(Test-Path -Path $Destination)) {
    New-Item -ItemType Directory -Path $Destination | Out-Null
    Write-Host "Folder created: $Destination"
}

# Empty the destination folder
Get-ChildItem -Path $Destination -Recurse -Force | Remove-Item -Recurse -Force

# If BaseDir wasn’t explicitly passed in, use IncludesFile directory
if (-not $PSBoundParameters.ContainsKey('BaseDir')) {
    $BaseDir = Split-Path -Parent (Resolve-Path $IncludesFile)
}

# Read includes list (ignore blank lines & comments)
$items = Get-Content $IncludesFile |
    ForEach-Object { $_.Trim() } |
    Where-Object { $_ -and -not $_.StartsWith("#") }

foreach ($item in $items) {
    if ([System.IO.Path]::IsPathRooted($item)) {
        # Absolute path (rare case)
        $sourcePath = $item
        $relative   = Split-Path $item -Leaf   # just take folder/file name
    } else {
        # Relative to BaseDir
        $sourcePath = Join-Path $BaseDir $item
        $relative   = $item                    # keep full relative path e.g. "frontend\dist"
    }

    if (-Not (Test-Path $sourcePath)) {
        Write-Warning "Skipping missing path: $sourcePath"
        continue
    }

    # Destination path should preserve the relative structure
    $targetPath = Join-Path $Destination $relative

    # Ensure the parent folder exists
    $targetDir = Split-Path $targetPath -Parent
    if (-not (Test-Path $targetDir)) {
        New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
    }

    Write-Host "Copying $sourcePath -> $targetPath" -ForegroundColor Cyan
    Copy-Item -Path $sourcePath -Destination $targetPath -Recurse -Force
}