param(
    [string]$TemplatePath = "",
    [string]$OutputPath = "",
    [string]$OperationsPath = ""
)

$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))
}

if (-not $TemplatePath) {
    $TemplatePath = "Report.pptx"
}

if (-not $OutputPath) {
    $OutputPath = $TemplatePath
}

$TemplatePath = Resolve-ProjectPath $TemplatePath
$OutputPath = Resolve-ProjectPath $OutputPath
$OperationsPath = Resolve-ProjectPath $OperationsPath

function Resolve-PythonCommand {
    $venvPython = Join-Path $root ".venv\Scripts\python.exe"
    if (Test-Path -LiteralPath $venvPython) {
        return ,$venvPython
    }
    if (Get-Command py -ErrorAction SilentlyContinue) {
        return @("py", "-3")
    }
    if (Get-Command python -ErrorAction SilentlyContinue) {
        return @("python")
    }
    return @()
}

function Has-NativeChartOps {
    param([string]$OpsPath)
    if (-not $OpsPath -or -not (Test-Path -LiteralPath $OpsPath)) {
        return $false
    }
    try {
        $ops = Get-Content -LiteralPath $OpsPath -Encoding UTF8 -Raw | ConvertFrom-Json
        if ($ops.PSObject.Properties.Name -contains "replace_native_charts") {
            return (@($ops.replace_native_charts).Count -gt 0)
        }
    }
    catch {
    }
    return $false
}

try {
    & "$root\scripts\render_template_com.ps1" -TemplatePath "$TemplatePath" -OutputPath "$OutputPath" -OperationsPath "$OperationsPath"
}
catch {
    $comError = $_
    $canFallback = Has-NativeChartOps -OpsPath $OperationsPath
    if (-not $canFallback) {
        Write-Error $comError
        exit 1
    }

    $pythonCmd = @(Resolve-PythonCommand)
    if ($pythonCmd.Count -eq 0) {
        Write-Error "COM render failed and python fallback is unavailable (python not found). Original error: $comError"
        exit 1
    }

    $fallbackScript = Join-Path $root "scripts\render_template_openxml.py"
    if (-not (Test-Path -LiteralPath $fallbackScript)) {
        Write-Error "COM render failed and fallback script is missing: $fallbackScript"
        exit 1
    }

    Write-Warning "COM render failed; falling back to python-pptx renderer."
    if ($pythonCmd.Count -eq 2) {
        & $pythonCmd[0] $pythonCmd[1] $fallbackScript --template "$TemplatePath" --output "$OutputPath" --operations "$OperationsPath"
    } else {
        & $pythonCmd[0] $fallbackScript --template "$TemplatePath" --output "$OutputPath" --operations "$OperationsPath"
    }
    if ($LASTEXITCODE -ne 0) {
        Write-Error "Fallback openxml renderer failed (exit=$LASTEXITCODE). Original COM error: $comError"
        exit 1
    }
}
