import Foundation
import Speech

/// POC: Test SFSpeechAnalyzer + SFSpeechRecognitionMetadata for speaker detection
/// Goal: Determine if ANE-accelerated speaker diarization is feasible

@main
struct SpeakerTest {
    static func main() {
        print("=== SFSpeechAnalyzer Speaker Detection POC ===")
        
        // 1. Check if running on ANE-capable hardware
        #if arch(arm64)
        print("Hardware: Apple Silicon ✅ (ANE available)")
        #else
        print("Hardware: Intel ❌ (No ANE)")
        #endif
        
        // 2. Check SFSpeechRecognizer on-device capability
        let locale = Locale(identifier: "en-US")
        let recognizerCheck = SFSpeechRecognizer(locale: locale)
        print("On-device recognition: \(recognizerCheck?.supportsOnDeviceRecognition == true ? "✅" : "❌")")
        
        // 3. Check SFSpeechAnalyzer capabilities via availability API
        if #available(macOS 14, *) {
            print("\n=== SFSpeechAnalyzer Analysis ===")
            let analyzerClass: AnyClass? = NSClassFromString("SFSpeechAnalyzer")
            print("SFSpeechAnalyzer: \(analyzerClass != nil ? "✅ Available" : "❌ Not available")")
            
            let mdClass: AnyClass? = NSClassFromString("SFSpeechRecognitionMetadata")
            print("SFSpeechRecognitionMetadata: \(mdClass != nil ? "✅ Available" : "❌ Not available")")
        }
        
        // 4. Test: Run ASR with SFSpeechRecognitionMetadata
        print("\n=== Real-world Test ===")
        let testFile = "/tmp/test_60s_b.wav"
        guard FileManager.default.fileExists(atPath: testFile) else {
            print("Test file not found: \(testFile)")
            return
        }
        
        let semaphore = DispatchSemaphore(value: 0)
        var detectedSpeakers: Set<String> = []
        
        print("Running ASR with speaker detection on 60s clip...")
        
        SFSpeechRecognizer.requestAuthorization { status in
            guard status == .authorized else {
                print("Authorization denied")
                semaphore.signal()
                return
            }
            
            let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
            guard recognizer.isAvailable else {
                print("Recognizer not available")
                semaphore.signal()
                return
            }
            
            let request = SFSpeechURLRecognitionRequest(url: URL(fileURLWithPath: testFile))
            request.shouldReportPartialResults = false
            request.requiresOnDeviceRecognition = true
            request.taskHint = .dictation
            
            let task = recognizer.recognitionTask(with: request) { result, error in
                if let error = error {
                    print("Recognition error: \(error.localizedDescription)")
                } else if let result = result, result.isFinal {
                    let text = result.bestTranscription.formattedString
                    print("Text: \(text.prefix(200))")
                    print("Segments: \(result.bestTranscription.segments.count)")
                    
                    // Check each segment for speaker metadata
                    if #available(macOS 14, *) {
                        for (i, seg) in result.bestTranscription.segments.enumerated() {
                            // Access metadata via KVC since it might be a private API
                            let md = seg.value(forKey: "metadata") as? NSObject
                            if let md = md {
                                let speakerId = md.value(forKey: "speakerID") as? String
                                let speakerName = md.value(forKey: "speakerName") as? String
                                let confidence = md.value(forKey: "speakerConfidence") as? Double
                                
                                if let sid = speakerId {
                                    detectedSpeakers.insert(sid)
                                    if i < 5 || i % 20 == 0 {
                                        print("  Seg[\(i)] speaker=\(sid) name=\(speakerName ?? "?") conf=\(confidence ?? 0) text=\"\(seg.substring.prefix(40))\"")
                                    }
                                }
                            }
                        }
                        
                        print("\nUnique speakers detected: \(detectedSpeakers)")
                        if detectedSpeakers.isEmpty {
                            print("⚠️ No speaker metadata found in recognition results")
                        }
                    } else {
                        print("macOS 14+ required for speaker metadata")
                    }
                }
                semaphore.signal()
            }
            
            // Wait
            while semaphore.wait(timeout: .now()) == .timedOut {
                RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1))
            }
            task.cancel()
        }
        
        semaphore.wait()
    }
}
