param(
    [Parameter(Mandatory = $true)]
    [string]$Slide,
    [Parameter(Mandatory = $true)]
    [string]$ReportMonth,
    [string]$ConfigPath = "",
    [int]$ReportYear = 0,
    [int]$CompareYear = 0,
    [ValidateSet("cumulative", "single")]
    [string]$MonthMode = "cumulative",
    [string]$TemplatePath = "",
    [string]$OutputPath = ""
)

$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $PSScriptRoot

function Resolve-ProjectPath {
    param([string]$PathValue)

    if (-not $PathValue) {
        return $PathValue
    }
    if ([System.IO.Path]::IsPathRooted($PathValue)) {
        return $PathValue
    }
    return [System.IO.Path]::GetFullPath((Join-Path $root $PathValue))
}

function Resolve-PythonCommand {
    if (Get-Command py -ErrorAction SilentlyContinue) {
        return @("py", "-3")
    }
    if (Get-Command python -ErrorAction SilentlyContinue) {
        return @("python")
    }
    throw "Python launcher not found. Please install py or python."
}

if (-not $ConfigPath) {
    $ConfigPath = "config.yaml"
}
if (-not $TemplatePath) {
    $TemplatePath = "Report.pptx"
}
if (-not $OutputPath) {
    $OutputPath = "output\generated-$($Slide.ToLower())-$ReportMonth-recrop.pptx"
}

$ConfigPath = Resolve-ProjectPath $ConfigPath
$TemplatePath = Resolve-ProjectPath $TemplatePath
$OutputPath = Resolve-ProjectPath $OutputPath

if (-not (Test-Path -LiteralPath $ConfigPath)) {
    throw "ConfigPath not found: $ConfigPath"
}
if (-not (Test-Path -LiteralPath $TemplatePath)) {
    throw "TemplatePath not found: $TemplatePath"
}

$pythonArgs = @(
    "$root\scripts\recrop_from_raw.py",
    "--config", "$ConfigPath",
    "--slide", "$Slide",
    "--report-month", "$ReportMonth",
    "--month-mode", "$MonthMode"
)
if ($ReportYear -gt 0) {
    $pythonArgs += @("--report-year", "$ReportYear")
}
if ($CompareYear -gt 0) {
    $pythonArgs += @("--compare-year", "$CompareYear")
}

$pythonCommand = Resolve-PythonCommand
if ($pythonCommand.Count -eq 2) {
    $opsOutput = & $pythonCommand[0] $pythonCommand[1] @pythonArgs 2>&1
} else {
    $opsOutput = & $pythonCommand[0] @pythonArgs 2>&1
}

if ($LASTEXITCODE -ne 0) {
    $details = ($opsOutput | ForEach-Object { "$_" }) -join [Environment]::NewLine
    throw "recrop_from_raw.py failed with exit code $LASTEXITCODE`n$details"
}

$opsPath = ($opsOutput | Select-Object -Last 1).ToString().Trim()
if (-not $opsPath) {
    throw "recrop_from_raw.py did not return an operations path."
}

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"
}

Write-Output $OutputPath
