import AppKit
import Vision
import AVFoundation
import ImageIO

func is67(_ text: String) -> Bool {
    let compact = text.unicodeScalars.filter { !CharacterSet.whitespacesAndNewlines.contains($0) && !CharacterSet.punctuationCharacters.contains($0) }.map(String.init).joined()
    return compact.contains("67")
}
@concurrent func recognize(_ data: Data) async throws -> Bool {
    guard let source = CGImageSourceCreateWithData(data as CFData, nil), let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { return false }
    let request = VNRecognizeTextRequest()
    request.recognitionLevel = .accurate
    request.usesLanguageCorrection = false
    request.recognitionLanguages = ["en-US"]
    request.minimumTextHeight = 0.02
    try VNImageRequestHandler(cgImage: image).perform([request])
    let observations = request.results ?? []
    if observations.contains(where: { observation in observation.topCandidates(3).contains { is67($0.string) } }) { return true }
    // Some handwriting is recognized as two neighboring text boxes.
    for a in observations { for b in observations where a !== b {
        let left = a.boundingBox, right = b.boundingBox
        if left.midX < right.midX && abs(left.midY-right.midY) < max(left.height,right.height)*0.5 && right.minX-left.maxX < 0.2 {
            if let first = a.topCandidates(1).first?.string, let second = b.topCandidates(1).first?.string, is67(first+second) { return true }
        }
    }}
    return false
}

@MainActor final class DrawingPad: NSView {
    var strokes: [[NSPoint]] = []
    var changed: (() -> Void)?
    override var isFlipped: Bool { true }
    override var acceptsFirstResponder: Bool { true }
    override func draw(_ rect: NSRect) {
        NSColor.white.setFill(); bounds.fill()
        NSColor.black.setStroke()
        for points in strokes where !points.isEmpty {
            let path = NSBezierPath(); path.lineWidth = 13; path.lineCapStyle = .round; path.lineJoinStyle = .round
            path.move(to: points[0]); if points.count == 1 { path.line(to: NSPoint(x: points[0].x+0.1,y: points[0].y)) }
            for p in points.dropFirst() { path.line(to: p) }; path.stroke()
        }
    }
    override func mouseDown(with event: NSEvent) { strokes.append([convert(event.locationInWindow, from:nil)]); needsDisplay=true; changed?() }
    override func mouseDragged(with event: NSEvent) { guard !strokes.isEmpty else{return}; strokes[strokes.count-1].append(convert(event.locationInWindow,from:nil));needsDisplay=true; changed?() }
    override func mouseUp(with event: NSEvent) { changed?() }
    func png() -> Data? {
        displayIfNeeded()
        guard let bitmap = bitmapImageRepForCachingDisplay(in:bounds) else{return nil}
        cacheDisplay(in:bounds,to:bitmap)
        return bitmap.representation(using:.png,properties:[:])
    }
}

@MainActor final class App: NSObject, NSApplicationDelegate {
    let window = NSWindow(contentRect:NSRect(x:0,y:0,width:820,height:640),styleMask:[.titled,.closable,.miniaturizable],backing:.buffered,defer:false)
    let pad = DrawingPad(frame:NSRect(x:24,y:92,width:772,height:440))
    let result = NSTextField(labelWithString:"Draw something…")
    let speech = AVSpeechSynthesizer()
    var sound = true, detected = false, revision = 0
    var pending: Task<Void,Never>?
    func applicationDidFinishLaunching(_ notification: Notification) {
        window.title="Brainrot Pad"; window.center()
        guard let content = window.contentView else{return}
        content.wantsLayer=true; content.layer?.backgroundColor=NSColor(calibratedRed:0.09,green:0.08,blue:0.15,alpha:1).cgColor
        let heading=NSTextField(labelWithString:"THE DOODLE DETECTOR")
        heading.frame=NSRect(x:24,y:586,width:770,height:28);heading.font = .boldSystemFont(ofSize:24);heading.textColor = .white;content.addSubview(heading)
        let hint=NSTextField(labelWithString:"Draw 67 big and clear. Pause for a moment. Mouse or trackpad works.")
        hint.frame=NSRect(x:24,y:551,width:770,height:24);hint.textColor = .lightGray;content.addSubview(hint)
        pad.wantsLayer=true;pad.layer?.cornerRadius=16;pad.layer?.masksToBounds=true;content.addSubview(pad)
        result.frame=NSRect(x:24,y:35,width:450,height:40);result.font = .boldSystemFont(ofSize:28);result.textColor = .white;content.addSubview(result)
        for (name,action,x) in [("Undo",#selector(undo),480.0),("Clear",#selector(clear),570.0),("Voice: on",#selector(toggleVoice(_:)),660.0)] {
            let b=NSButton(title:name,target:self,action:action);b.frame=NSRect(x:x,y:37,width:name.hasPrefix("Voice") ? 136:80,height:34);b.bezelStyle = .rounded;content.addSubview(b)
        }
        pad.changed = { [weak self] in self?.schedule() }
        window.makeKeyAndOrderFront(nil);NSApp.activate(ignoringOtherApps:true)
    }
    func schedule() {
        revision += 1; let version=revision
        pending?.cancel()
        result.stringValue="Thinking…"; result.textColor = .white
        pending=Task { [weak self] in
            do { try await Task.sleep(for:.milliseconds(800)) } catch {return}
            guard let self, !Task.isCancelled, let data=self.pad.png() else{return}
            do {
                let found=try await recognize(data)
                guard !Task.isCancelled, self.revision==version else{return}
                self.result.stringValue=found ? "brainrot kid 🫵😂" : "Keep drawing…"
                self.result.textColor=found ? .systemYellow:.white
                if found && !self.detected && self.sound {
                    let words=AVSpeechUtterance(string:"brainrot kid");words.rate=0.48;self.speech.speak(words)
                }
                self.detected=found
            } catch {
                guard self.revision==version else{return}
                self.result.stringValue="Couldn't read that. Try again."
            }
        }
    }
    @objc func clear(){pending?.cancel();revision += 1;pad.strokes=[];pad.needsDisplay=true;detected=false;speech.stopSpeaking(at:.immediate);result.stringValue="Draw something…";result.textColor = .white}
    @objc func undo(){guard !pad.strokes.isEmpty else{return};pad.strokes.removeLast();pad.needsDisplay=true;schedule()}
    @objc func toggleVoice(_ sender:NSButton){sound.toggle();sender.title=sound ? "Voice: on":"Voice: off";if !sound {speech.stopSpeaking(at:.immediate)}}
    func applicationShouldTerminateAfterLastWindowClosed(_ sender:NSApplication)->Bool{true}
    func applicationWillTerminate(_ notification:Notification){pending?.cancel();speech.stopSpeaking(at:.immediate)}
}

@main struct Launcher {
@MainActor static func main() {
if CommandLine.arguments.contains("--self-test") {
    assert(is67("67"));assert(is67("6 7"));assert(is67("6\n7"));assert(!is67("76"));assert(!is67("6"));assert(!is67("hello"))
    print("PASS: target parsing and negative cases")
} else {
    let application=NSApplication.shared
    application.setActivationPolicy(.regular)
    let menu=NSMenu(),appMenu=NSMenu(),root=NSMenuItem();root.submenu=appMenu;menu.addItem(root)
    appMenu.addItem(withTitle:"Quit Brainrot Pad",action:#selector(NSApplication.terminate(_:)),keyEquivalent:"q");application.mainMenu=menu
    let delegate=App();application.delegate=delegate;application.run()
}

}}
