import AVFoundation
import Foundation
import MastermindPOCCore

final class MicrophoneCaptureEngine {
    private let engine = AVAudioEngine()
    private let onFrame: (PCMFrame) -> Void
    private let onError: (String) -> Void
    private var isRunning = false

    init(onFrame: @escaping (PCMFrame) -> Void, onError: @escaping (String) -> Void) {
        self.onFrame = onFrame
        self.onError = onError
    }

    func start() throws {
        guard !isRunning else {
            return
        }

        let inputNode = engine.inputNode
        let format = inputNode.outputFormat(forBus: 0)

        inputNode.removeTap(onBus: 0)
        inputNode.installTap(onBus: 0, bufferSize: 1024, format: format) { [weak self] buffer, _ in
            guard let self else {
                return
            }

            if let frame = MicrophonePCMConverter.extractFrame(from: buffer) {
                self.onFrame(frame)
            }
        }

        do {
            try engine.start()
            isRunning = true
        } catch {
            inputNode.removeTap(onBus: 0)
            onError("Microphone start failed: \(error.localizedDescription)")
            throw error
        }
    }

    func stop() {
        guard isRunning else {
            return
        }

        engine.inputNode.removeTap(onBus: 0)
        engine.stop()
        isRunning = false
    }
}
