import Foundation
import AppKit
import Vision

let args = CommandLine.arguments
if args.count < 2 { fputs("usage: vision_ocr <image> [lang]\n", stderr); exit(1) }
let path = args[1]
let lang = args.count > 2 ? args[2] : "zh-Hans"
guard let image = NSImage(contentsOfFile: path),
      let tiff = image.tiffRepresentation,
      let rep = NSBitmapImageRep(data: tiff),
      let cg = rep.cgImage else { fputs("image load failed\n", stderr); exit(2) }
let req = VNRecognizeTextRequest()
req.recognitionLevel = .accurate
req.usesLanguageCorrection = true
req.recognitionLanguages = [lang, "en-US"]
let handler = VNImageRequestHandler(cgImage: cg, options: [:])
do {
  try handler.perform([req])
  if let results = req.results {
    for obs in results {
      if let cand = obs.topCandidates(1).first { print(cand.string) }
    }
  }
} catch { fputs("ocr failed: \(error)\n", stderr); exit(3) }
