<#
用途：
- 同步 S11（Campaign-年货节）来源数据，落盘校验结果并生成 render-ops。
- 可选直接渲染 PPT 并执行 compare。
#>

param(
    [string]$ConfigPath = "C:\Users\niuniu\.codex\vip-report\config.yaml",
    [string]$Slides = "S11",
    [string]$ReportMonth = "",
    [int]$ReportYear = 0,
    [int]$CompareYear = 0,
    [int]$ShopId = 20,
    [switch]$DisableStrictJanuaryCheck,
    [switch]$Render,
    [string]$OutputDir = "",
    [string]$OutputPath = "C:\workspace\cursor\output\vip-report\generated-campaign-s11-live.pptx",
    [string]$CompareOutputPath = "C:\workspace\cursor\output\vip-report\generated-campaign-s11-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.campaign-s11.live.json"
$templatePath = "C:\Users\niuniu\Desktop\Report.pptx"

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-campaign-s11-live.pptx") {
    $OutputPath = Join-Path $resolvedOutputDir "generated-campaign-s11-live.pptx"
}
if ($OutputDir -and $CompareOutputPath -eq "C:\workspace\cursor\output\vip-report\generated-campaign-s11-live.compare.json") {
    $CompareOutputPath = Join-Path $resolvedOutputDir "generated-campaign-s11-live.compare.json"
}

$pythonArgs = @(
    "$root\scripts\sync_campaign_s11_assets.py",
    "--config", "$ConfigPath",
    "--slides", "$Slides",
    "--shop-id", "$ShopId"
)
if ($ReportMonth) {
    $pythonArgs += @("--report-month", "$ReportMonth")
}
if ($ReportYear -gt 0) {
    $pythonArgs += @("--report-year", "$ReportYear")
}
if ($CompareYear -gt 0) {
    $pythonArgs += @("--compare-year", "$CompareYear")
}
if ($DisableStrictJanuaryCheck) {
    $pythonArgs += @("--disable-strict-january-check")
}
$pythonArgs += @("--output-dir", "$resolvedOutputDir")

python @pythonArgs
if ($LASTEXITCODE -ne 0) {
    throw "sync_campaign_s11_assets.py failed with exit code $LASTEXITCODE"
}

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