import Foundation
import AppKit
import PDFKit
let root = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("pdf-overlay-lab-" + UUID().uuidString)
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }
func create(_ name: String, includeToken: Bool, cover: Bool) -> URL {
    let url = root.appendingPathComponent(name + ".pdf")
    var box = CGRect(x: 0, y: 0, width: 400, height: 220)
    let context = CGContext(url as CFURL, mediaBox: &box, nil)!
    context.beginPDFPage(nil)
    NSGraphicsContext.saveGraphicsState()
    NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
    let style: [NSAttributedString.Key: Any] = [.font:NSFont.systemFont(ofSize:20), .foregroundColor:NSColor.black]
    ("Synthetic example only" as NSString).draw(at:NSPoint(x:20,y:170),withAttributes:style)
    if includeToken { ("DEMO-CLIENT-7421" as NSString).draw(at:NSPoint(x:20,y:100),withAttributes:style) }
    if cover { context.setFillColor(NSColor.black.cgColor);context.fill(CGRect(x:15,y:95,width:310,height:35)) }
    NSGraphicsContext.restoreGraphicsState();context.endPDFPage();context.closePDF()
    return url
}
var results: [[String: Any]] = []
for (name, token, cover) in [("original",true,false),("painted-overlay",true,true),("regenerated-without-token",false,true)] {
    let url=create(name,includeToken:token,cover:cover)
    let doc=PDFDocument(url:url)!
    let extracted=doc.string ?? ""
    let present=extracted.contains("DEMO-CLIENT-7421")
    precondition(present==token)
    results.append(["case":name,"token_extractable":present,"pages":doc.pageCount,"file_bytes":try Data(contentsOf:url).count])
}
let output:[String:Any] = ["passed":true,"os":ProcessInfo.processInfo.operatingSystemVersionString,"cases":results,"limits":"Synthetic CoreGraphics PDF and PDFKit extraction only; no Preview/Acrobat UI, scans, OCR, signatures, or exhaustive sanitization tested."]
let data=try JSONSerialization.data(withJSONObject:output,options:[.prettyPrinted,.sortedKeys]);print(String(data:data,encoding:.utf8)!)
