import Foundation
import Vision
import ArgumentParser
import AppKit

/// POC: Test Apple Vision Framework OCR (VNRecognizeTextRequest) vs PaddleOCR
@main
struct VisionOCRTest: ParsableCommand {
    @Argument(help: "Input image path")
    var inputPath: String

    @Option(name: .long, help: "Recognition level (.fast or .accurate, default .accurate)")
    var level: String = "accurate"

    mutating func run() throws {
        let startTime = Date()
        print("=== Apple Vision Framework OCR POC ===")
        #if arch(arm64)
        print("HW: Apple Silicon ✅")
        #endif

        guard let image = NSImage(contentsOfFile: inputPath) else {
            print("Error: cannot load image"); return
        }
        guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
            print("Error: cannot get CGImage"); return
        }
        print("Image: \(cgImage.width)x\(cgImage.height)")
        let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])

        // VNRecognizeTextRequest
        print("\n--- VNRecognizeTextRequest ---")
        let req = VNRecognizeTextRequest()
        if level == "fast" {
            req.recognitionLevel = .fast
        } else {
            req.recognitionLevel = .accurate
        }
        req.usesLanguageCorrection = true
        req.preferBackgroundProcessing = true

        try handler.perform([req])

        guard let results = req.results else {
            print("No OCR results"); return
        }

        print("Text blocks: \(results.count)")
        var totalChars = 0
        for (i, obs) in results.enumerated() {
            guard let candidate = obs.topCandidates(1).first else { continue }
            let text = candidate.string
            let conf = candidate.confidence
            let bb = obs.boundingBox
            totalChars += text.count
            if i < 20 {
                print("  [\(i)] conf=\(String(format: "%.3f", conf)) bbox=(\(String(format: "%.3f", bb.origin.x)),\(String(format: "%.3f", bb.origin.y)),\(String(format: "%.3f", bb.size.width)),\(String(format: "%.3f", bb.size.height))) \"\(text.prefix(80))\"")
            }
        }
        print("  ... \(results.count) total, \(totalChars) chars")

        // Check language support
        print("\n--- Language Support ---")
        let supported = (try? VNRecognizeTextRequest.supportedRecognitionLanguages(for: .accurate, revision: VNRecognizeTextRequest.currentRevision)) ?? []
        print("Supported languages (\(supported.count)): \(supported.prefix(10).joined(separator: ", "))...")

        let elapsed = Date().timeIntervalSince(startTime)
        print("\nTime: \(String(format: "%.2f", elapsed))s")
        print("=== Done ===")
    }
}
