param(
    [string]$ConfigPath = "C:\Users\niuniu\.codex\vip-report\config.yaml",
    [string]$Slides = "S13",
    [string]$ReportMonth = "",
    [int]$ReportYear = 0,
    [int]$CompareYear = 0,
    [switch]$Render,
    [string]$OutputDir = "",
    [string]$OutputPath = "C:\workspace\cursor\output\vip-report\generated-warehouse-100060-live.pptx",
    [string]$CompareOutputPath = "C:\workspace\cursor\output\vip-report\generated-warehouse-100060-live.compare.json"
)

$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $PSScriptRoot
$resolvedOutputDir = if ($OutputDir) { [System.IO.Path]::GetFullPath($OutputDir) } else { "C:\workspace\cursor\output\vip-report" }
$opsPath = Join-Path $resolvedOutputDir "render-ops.warehouse-100060.live.json"
$localConfigPath = Join-Path $root "config.yaml"
if (-not (Test-Path -LiteralPath $resolvedOutputDir)) {
    New-Item -ItemType Directory -Path $resolvedOutputDir -Force | Out-Null
}
if ($OutputDir -and $OutputPath -eq "C:\workspace\cursor\output\vip-report\generated-warehouse-100060-live.pptx") {
    $OutputPath = Join-Path $resolvedOutputDir "generated-warehouse-100060-live.pptx"
}
if ($OutputDir -and $CompareOutputPath -eq "C:\workspace\cursor\output\vip-report\generated-warehouse-100060-live.compare.json") {
    $CompareOutputPath = Join-Path $resolvedOutputDir "generated-warehouse-100060-live.compare.json"
}
if (-not (Test-Path -LiteralPath $ConfigPath) -and (Test-Path -LiteralPath $localConfigPath)) {
    $ConfigPath = $localConfigPath
}

$templatePath = "C:\Users\niuniu\Desktop\Report.pptx"
$downloadTemplatePath = "C:\Users\allen.wang\Downloads\Report.pptx"
$fallbackTemplatePath = Join-Path $root "output\Report.clean.pptx"
if (-not (Test-Path -LiteralPath $templatePath) -and (Test-Path -LiteralPath $downloadTemplatePath)) {
    $templatePath = $downloadTemplatePath
}
if (-not (Test-Path -LiteralPath $templatePath) -and (Test-Path -LiteralPath $fallbackTemplatePath)) {
    $templatePath = $fallbackTemplatePath
}

$pythonArgs = @(
    "$root\scripts\sync_warehouse_100060_assets.py",
    "--config", "$ConfigPath",
    "--slides", "$Slides"
)
if ($ReportMonth) {
    $pythonArgs += @("--report-month", "$ReportMonth")
}
if ($ReportYear -gt 0) {
    $pythonArgs += @("--report-year", "$ReportYear")
}
if ($CompareYear -gt 0) {
    $pythonArgs += @("--compare-year", "$CompareYear")
}
$pythonArgs += @("--output-dir", "$resolvedOutputDir")
python @pythonArgs

if ($Render) {
    powershell -ExecutionPolicy Bypass -File "$root\bin\vip-report-render.ps1" -TemplatePath "$templatePath" -OutputPath "$OutputPath" -OperationsPath "$opsPath" | Out-Null
    python "$root\scripts\compare_pptx.py" "$templatePath" "$OutputPath" --output "$CompareOutputPath"
    Write-Output $OutputPath
    Write-Output $CompareOutputPath
} else {
    Write-Output $opsPath
}
