import path from "node:path"
import { fileURLToPath } from "node:url"
import { AgentConfig, ScanResult } from "../types.js"
import { commandExists, runCommand } from "../commands.js"

const currentFile = fileURLToPath(import.meta.url)
const agentRoot = path.resolve(path.dirname(currentFile), "../..")
const postprocessScript = path.join(agentRoot, "scripts/opencv_postprocess.py")

const extensionMimeTypes: Record<string, string> = {
    ".pdf": "application/pdf",
    ".png": "image/png",
    ".tif": "image/tiff",
    ".tiff": "image/tiff",
    ".jpg": "image/jpeg",
    ".jpeg": "image/jpeg",
}

const ensureOutputExtension = (filename: string, format: AgentConfig["scanFormat"]) => {
    const ext = path.extname(filename)
    if (ext) return filename
    return `${filename}.${format}`
}

export const hasOpenCvPostprocessRuntime = async (config: AgentConfig) => {
    if (!await commandExists(config.postprocessPython)) return false

    const result = await runCommand(config.postprocessPython, [
        "-c",
        "import cv2, PIL, numpy",
    ], { timeoutMs: 10_000 })

    return result.code === 0
}

export const postprocessScan = async (
    config: AgentConfig,
    inputPath: string,
    outputFilename: string,
    outputFormat: AgentConfig["scanFormat"],
    profile: AgentConfig["postprocessProfile"]
): Promise<ScanResult> => {
    const filename = ensureOutputExtension(outputFilename, outputFormat)
    const outputPath = path.join(config.workDir, filename)

    const result = await runCommand(config.postprocessPython, [
        postprocessScript,
        "--input",
        inputPath,
        "--output",
        outputPath,
        "--profile",
        profile,
    ], { timeoutMs: 5 * 60 * 1000 })

    if (result.code !== 0) {
        throw new Error(result.stderr || `OpenCV-Nachbearbeitung wurde mit Code ${result.code} beendet`)
    }

    const extension = path.extname(outputPath).toLowerCase()
    return {
        path: outputPath,
        filename,
        mimeType: extensionMimeTypes[extension] || "application/octet-stream",
    }
}
