import Foundation
import PoseCore
import Darwin

// Vision can raise an Objective-C exception. Keep inference outside the editor process.
enum RetryWorker {
    static func run(request: RetryRequest, helper: URL, directory: URL) throws -> DetectionRetry {
        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
        let input = directory.appendingPathComponent("request.json")
        let output = directory.appendingPathComponent("result.json")
        try JSONEncoder().encode(request).write(to: input, options: .atomic)
        let log = directory.appendingPathComponent("process.log")
        FileManager.default.createFile(atPath: log.path, contents: nil)
        let handle = try FileHandle(forWritingTo: log)
        defer { try? handle.close() }
        let process = Process()
        process.executableURL = helper; process.arguments = ["redetect", input.path, output.path]
        process.standardOutput = handle; process.standardError = handle
        try process.run()
        let deadline = Date().addingTimeInterval(60)
        while process.isRunning && Date() < deadline { Thread.sleep(forTimeInterval: 0.1) }
        if process.isRunning {
            process.terminate()
            Thread.sleep(forTimeInterval: 0.5)
            if process.isRunning { kill(process.processIdentifier, SIGKILL) }
            throw PoseError.invalidInput("Detection timed out. Your corrections are preserved.")
        }
        guard process.terminationStatus == 0 else { throw PoseError.invalidInput("Detection failed. Your corrections are preserved; retry diagnostics are saved locally.") }
        return try JSONDecoder().decode(DetectionRetry.self, from: Data(contentsOf: output))
    }
}
