import Foundation
import PoseCore
import Darwin

/// Keep Vision exceptions and long-running inference out of the editor process.
enum SessionAnalysisWorker {
    static func run(manifest: URL, output: URL, helper: URL, timeout: TimeInterval = 900) throws {
        let log = output.appendingPathExtension("log")
        guard FileManager.default.createFile(atPath: log.path, contents: nil) else {
            throw PoseError.invalidInput("Cannot create the folder analysis log.")
        }
        let handle = try FileHandle(forWritingTo: log)
        defer { try? handle.close() }
        let process = Process()
        process.executableURL = helper
        process.arguments = ["feasibility", manifest.path, output.path]
        process.standardOutput = handle; process.standardError = handle
        try process.run()
        let deadline = Date().addingTimeInterval(timeout)
        while process.isRunning && Date() < deadline { Thread.sleep(forTimeInterval: 0.1) }
        if process.isRunning {
            process.terminate()
            Thread.sleep(forTimeInterval: 0.3)
            if process.isRunning { kill(process.processIdentifier, SIGKILL) }
            process.waitUntilExit()
            throw PoseError.invalidInput("Folder analysis timed out. Originals and saved reviews are unchanged. See \(log.lastPathComponent).")
        }
        process.waitUntilExit()
        // Exit 2 means a completed report includes unavailable/error detections, still reviewable.
        guard process.terminationReason == .exit,
              process.terminationStatus == 0 || process.terminationStatus == 2 else {
            throw PoseError.invalidInput("Folder analysis failed. See \(log.lastPathComponent). Relaunch or rescan to retry.")
        }
    }
}
