import Foundation
import Speech

/// Test: Use KVC to check for speaker metadata on SFSpeechRecognitionResult
@main
struct SpeakerMetaTest {
    static func main() {
        print("=== Speaker Metadata Test ===")
        
        let testFile = "/tmp/test_60s_b.wav"
        guard FileManager.default.fileExists(atPath: testFile) else {
            print("Test file not found")
            return
        }
        
        let semaphore = DispatchSemaphore(value: 0)
        var done = false
        
        SFSpeechRecognizer.requestAuthorization { status in
            guard status == .authorized else {
                print("Authorization: \(status.rawValue)")
                semaphore.signal()
                return
            }
            print("Authorization: ✅")
            
            let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))!
            recognizer.supportsOnDeviceRecognition ? print("On-device: ✅") : print("On-device: ❌ (will use server)")
            
            let request = SFSpeechURLRecognitionRequest(url: URL(fileURLWithPath: testFile))
            request.shouldReportPartialResults = false
            request.requiresOnDeviceRecognition = false
            request.taskHint = .dictation
            
            print("Starting recognition...")
            let task = recognizer.recognitionTask(with: request) { result, error in
                if let error = error {
                    print("Error: \(error.localizedDescription)")
                } else if let result = result, result.isFinal {
                    print("Recognition complete: \(result.bestTranscription.segments.count) raw segments")
                    
                    // Check for metadata on the result object
                    let resultMetadata = result.value(forKey: "metadata") as? NSObject
                    print("Result metadata: \(resultMetadata != nil ? "✅" : "❌")")
                    if let rm = resultMetadata {
                        print("  Result metadata class: \(type(of: rm))")
                        // Dump all KVC values
                        for key in ["speakerID", "speakerName", "speakerConfidence", "voiceProfileID", "speaker"] {
                            if let val = rm.value(forKey: key) {
                                print("  result.\(key) = \(val)")
                            }
                        }
                    }
                    
                    // Check each segment for metadata
                    var speakerCount = 0
                    for (i, seg) in result.bestTranscription.segments.enumerated() {
                        let segMetadata = seg.value(forKey: "metadata") as? NSObject
                        if let sm = segMetadata {
                            if i < 3 {
                                print("Seg[\(i)] metadata class: \(type(of: sm))")
                                // Try common keys
                                for key in ["speakerID", "speaker", "voice", "speakerConfidence", "speakerName"] {
                                    if let val = sm.value(forKey: key) {
                                        print("  seg.\(key) = \(val)")
                                        speakerCount += 1
                                    }
                                }
                            }
                        }
                    }
                    
                    if speakerCount == 0 {
                        print("No speaker metadata found on any segment")
                    } else {
                        print("Found speaker metadata on segments: ✅")
                    }
                    
                    // Also check all KVC keys on first segment
                    if let firstSeg = result.bestTranscription.segments.first {
                        print("\nAll KVC keys on first segment:")
                        let keys = ["metadata", "speaker", "voice", "recognition", "analysis", "audio"]
                        for key in keys {
                            if let val = firstSeg.value(forKey: key) {
                                print("  \(key): \(type(of: val)) = \(val)")
                            }
                        }
                    }
                }
                done = true
                semaphore.signal()
            }
            
            // Run loop until done
            while !done {
                RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.1))
            }
            task.cancel()
            
            semaphore.signal()
        }
        
        semaphore.wait()
        print("Done")
    }
}
