$ErrorActionPreference = "Stop"

Write-Host "[1/6] Collecting environment info..." -ForegroundColor Cyan
$report = @()
$report += "# ETL Manager Environment Report"
$report += "Timestamp: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
$report += ""

Write-Host "[2/6] Resolving python/pip..." -ForegroundColor Cyan
$report += "## Executables"
$py = (Get-Command python -ErrorAction SilentlyContinue)
$pip = (Get-Command pip -ErrorAction SilentlyContinue)
if ($py) { $report += "python: $($py.Source)" } else { $report += "python: NOT FOUND" }
if ($pip) { $report += "pip: $($pip.Source)" } else { $report += "pip: NOT FOUND" }
$report += ""

Write-Host "[3/6] Python details..." -ForegroundColor Cyan
$report += "## Python info"
$report += (python -c "import sys, platform; print('version='+sys.version.replace('\n',' ')); print('executable='+sys.executable); print('prefix='+sys.prefix); print('base_prefix='+sys.base_prefix); print('arch='+platform.architecture()[0]); print('platform='+platform.platform())" 2>&1)
$report += ""

Write-Host "[4/6] pip details..." -ForegroundColor Cyan
$report += "## pip"
$report += (python -m pip --version 2>&1)
$report += ""

Write-Host "[5/6] PySide6 details..." -ForegroundColor Cyan
$report += "## PySide6"
$pyside = @'
try:
 import PySide6
 from PySide6 import QtCore
 print('PySide6='+PySide6.__version__)
 print('Qt='+QtCore.qVersion())
 print('PySide6_path='+PySide6.__file__)
 print('Qt_plugins_path='+QtCore.QLibraryInfo.path(QtCore.QLibraryInfo.PluginsPath))
except Exception as e:
 print('PySide6_import_error='+repr(e))
'@
$report += ($pyside | python - 2>&1)
$report += ""

Write-Host "[6/6] Installed packages..." -ForegroundColor Cyan
$report += "## Installed packages (freeze)"
$report += (python -m pip list --format=freeze 2>&1)

$reportPath = "D:\env_report_local.txt"
if (-not (Test-Path "D:\")) {
  Write-Host "[WARN] D: not found, fallback to current directory." -ForegroundColor Yellow
  $reportPath = ".\env_report_local.txt"
}
$reportDir = Split-Path $reportPath
if ($reportDir -and -not (Test-Path $reportDir)) {
  New-Item -ItemType Directory -Path $reportDir -Force | Out-Null
}

Write-Host "[WRITE] $reportPath" -ForegroundColor Green
$report -join "`n" | Set-Content -Path $reportPath -Encoding UTF8
Write-Host "[DONE]" -ForegroundColor Green
Write-Output $reportPath
