# Synopsis: Parses dragged-and-dropped files.
# Description: Automatically handles .pdf, .csv, and .xlsx via Python backend, falls back to native/base64 for others.

param([string]$FilePath)

if (Test-Path -LiteralPath $FilePath) {
    try {
        $Extension = (Get-Item -LiteralPath $FilePath).Extension
        
        # Deploy native Python parsing for complex non-base64 types
        if ($Extension -match '(?i)\.(pdf|xlsx|xls|csv)$') {
            $PyScript = Join-Path (Split-Path $PSScriptRoot -Parent) "Python\parse_binary_file.py"
            $BaseDir = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
            $RuntimeConfig = Join-Path $BaseDir "Config\python_runtime.json"
            $Candidates = @()
            $PortablePy = Join-Path $BaseDir "Tools\Python\python.exe"
            if (Test-Path $PortablePy) { $Candidates += ,@($PortablePy) }
            if (Test-Path $RuntimeConfig) {
                try {
                    $Runtime = Get-Content -LiteralPath $RuntimeConfig -Raw | ConvertFrom-Json
                    if ($Runtime.command) {
                        $Command = [string]$Runtime.command
                        if ($Command -match '^[A-Za-z]:\\|^\\') { $ResolvedCommand = $Command } else { $ResolvedCommand = Join-Path $BaseDir $Command }
                        $ArgsPrefix = @()
                        if ($Runtime.args) { $ArgsPrefix = ([string]$Runtime.args) -split ' ' | Where-Object { $_ } }
                        $Candidates += ,(@($ResolvedCommand) + $ArgsPrefix)
                    }
                } catch { }
            }
            $Candidates += ,@("py.exe", "-3")
            $Candidates += ,@("python.exe")

            if (Test-Path $PyScript) {
                foreach ($Candidate in $Candidates) {
                    $Exe = $Candidate[0]
                    if ((Test-Path $Exe) -or (Get-Command $Exe -ErrorAction SilentlyContinue)) {
                        $ExeArgs = @()
                        if ($Candidate.Count -gt 1) { $ExeArgs = $Candidate[1..($Candidate.Count - 1)] }
                        $ResultJson = & $Exe @ExeArgs $PyScript $FilePath 2>&1
                        return $ResultJson
                    }
                }
                return (@{ "error" = "No Python runtime found for binary parser." } | ConvertTo-Json -Compress)
            }
        }

        # Fallback to standard base64 parsing for images and other office formats
        if ($Extension -match '(?i)\.(png|jpg|jpeg|docx|pptx|zip)$') {
            [byte[]]$Bytes = $null
            if ($PSVersionTable.PSVersion.Major -ge 6) {
                $Bytes = [byte[]](Get-Content -LiteralPath $FilePath -AsByteStream -ReadCount 0)
            } else {
                $Bytes = [byte[]](Get-Content -LiteralPath $FilePath -Encoding Byte -ReadCount 0)
            }
            
            $Base64 = [System.Convert]::ToBase64String($Bytes)
            $ExtClean = $Extension -replace '^\.', ''
            
            $MimeType = "application/octet-stream"
            if ($ExtClean -match '(?i)(png|jpg|jpeg)') { $MimeType = "image/$ExtClean" }
            elseif ($ExtClean -match '(?i)docx') { $MimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }
            elseif ($ExtClean -match '(?i)pptx') { $MimeType = "application/vnd.openxmlformats-officedocument.presentationml.presentation" }

            $ComplexPayload = @(
                @{ "type" = "text"; "text" = "[UPLOADED BINARY FILE: $FilePath]" },
                @{ "type" = "image_url"; "image_url" = @{ "url" = "data:$MimeType;base64,$Base64" } }
            )
            return ($ComplexPayload | ConvertTo-Json -Depth 10 -Compress)
        } else {
            $DroppedContent = Get-Content -LiteralPath $FilePath -Raw
            $TextPayload = "[UPLOADED FILE: $FilePath]`n" + $DroppedContent
            return (@{ "text_payload" = $TextPayload } | ConvertTo-Json -Compress)
        }
    } catch {
        return (@{ "error" = $_.Exception.Message } | ConvertTo-Json -Compress)
    }
} else {
    return (@{ "error" = "File not found." } | ConvertTo-Json -Compress)
}

