import Foundation
import Vision
import AppKit

// 用法: swift decode_qr.swift <img1> <img2> ...
for path in CommandLine.arguments.dropFirst() {
    guard let img = NSImage(contentsOfFile: path),
          let cg = img.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
        print("\(path)\tERR\t无法读取")
        continue
    }
    let req = VNDetectBarcodesRequest()
    let handler = VNImageRequestHandler(cgImage: cg, options: [:])
    do {
        try handler.perform([req])
        let obs = (req.results as? [VNBarcodeObservation]) ?? []
        if obs.isEmpty {
            print("\(path)\tERR\t未识别到码")
        } else {
            for o in obs {
                print("\(path)\t\(o.symbology.rawValue)\t\(o.payloadStringValue ?? "(空)")")
            }
        }
    } catch {
        print("\(path)\tERR\t\(error.localizedDescription)")
    }
}
