import Foundation
import Capacitor
import Vision
import UIKit

/// On-device OCR using Apple's Vision framework. The image is decoded from the
/// base64 the web layer passes, recognized ON THE DEVICE, and only the resulting
/// text is returned. The image is never written to disk and never uploaded
/// (IRIS Chat invariant #8). The returned text is masked on-device by the web
/// layer before anything else is done with it.
@objc(IrisOcrPlugin)
public class IrisOcrPlugin: CAPPlugin {

    @objc func recognizeText(_ call: CAPPluginCall) {
        guard let b64 = call.getString("image"),
              let data = Data(base64Encoded: b64),
              let image = UIImage(data: data),
              let cgImage = image.cgImage else {
            call.reject("Could not decode the image")
            return
        }

        let request = VNRecognizeTextRequest { (req, err) in
            if let err = err {
                call.reject("OCR failed: \(err.localizedDescription)")
                return
            }
            let observations = (req.results as? [VNRecognizedTextObservation]) ?? []
            let lines = observations.compactMap { $0.topCandidates(1).first?.string }
            call.resolve(["text": lines.joined(separator: "\n")])
        }
        request.recognitionLevel = .accurate
        request.usesLanguageCorrection = true
        // English + Filipino handwriting/print; extend as needed for the pilot.
        if #available(iOS 13.0, *) {
            request.recognitionLanguages = ["en-US", "fil-PH"]
        }

        let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
        DispatchQueue.global(qos: .userInitiated).async {
            do {
                try handler.perform([request])
            } catch {
                call.reject("OCR failed: \(error.localizedDescription)")
            }
        }
    }
}
