// macOS-only offline smoke test of the actual generated PDF, including decoding its QR.
import Foundation
import PDFKit
import Vision
import AppKit

guard (3...4).contains(CommandLine.arguments.count),
      let document = PDFDocument(url: URL(fileURLWithPath: CommandLine.arguments[1])),
      let page = document.page(at: 0) else { fatalError("Pass input PDF and output PNG paths") }
guard document.pageCount == 1 else { fatalError("Receipt unexpectedly spans multiple pages") }
let content = document.string ?? ""
let unsigned = CommandLine.arguments.count == 4 && CommandLine.arguments[3] == "--unsigned-historical"
let requiredText = unsigned ? ["HISTÓRICO", "4,465.00", "SIN SELLO DIGITAL", "CFDI"] : ["RECIBO DE PAGO", "4,465.00", "SELLO DIGITAL", "VERIFICACIÓN DIGITAL", "RSA-SHA256", "CFDI"]
for required in requiredText {
    guard content.contains(required) else { fatalError("Missing PDF text: \(required)") }
}
let image = page.thumbnail(of: NSSize(width: 1530, height: 1980), for: .mediaBox)
guard let data = image.tiffRepresentation, let bitmap = NSBitmapImageRep(data: data), let cgImage = bitmap.cgImage else { fatalError("Cannot render PDF") }
try bitmap.representation(using: .png, properties: [:])!.write(to: URL(fileURLWithPath: CommandLine.arguments[2]))
let request = VNDetectBarcodesRequest()
request.usesCPUOnly = true
request.revision = VNDetectBarcodesRequestRevision1
request.symbologies = [.qr]
try VNImageRequestHandler(cgImage: cgImage).perform([request])
let values = (request.results ?? []).compactMap { $0.payloadStringValue }
if unsigned {
    guard values.isEmpty, !content.contains("RSA-SHA256") else { fatalError("Historical unsigned PDF must not claim a signature or QR") }
    print("Historical PDF: one page, unsigned warning verified, no QR or signature claimed.")
} else {
    guard values.count == 1, values[0].hasPrefix("https://receipts.example.test/verificar/recibo/"), values[0].split(separator: "/").last?.count == 64 else { fatalError("PDF QR did not decode to the public verifier") }
    print("PDF: one page, text verified, QR decoded locally to the correct verification endpoint.")
}
