import numpy as np
import sounddevice as sd
from .shared import audio_q


class SoundInputStream:
    def __init__(self, cfg: dict):
        default_in = sd.default.device[0]
        if cfg["device"] == "default":
            cfg["device"] = None
        else:
            cfg["device"] = int(cfg["device"])
        # print(f"🎛️ 默认输入设备ID: {default_in} | 当前使用: {cfg["device"] if cfg["device"] is not None else cfg["device"]}")
        
        self.stream = sd.InputStream(
            device=cfg["device"],
            channels=cfg['channels'],
            samplerate=cfg['sample_rate'],
            dtype=cfg['dtype'],
            blocksize=cfg['blocksize'],
            latency=cfg['latency'],
            callback=self.audio_callback
            )
        self.stream.start()
        print("SoundInputStream start")
    
    def audio_callback(self, indata, frames, time_info, status):
        if status:
            # 轻量报告即可，避免阻塞回调
            pass
        # indata: shape (frames, channels), int16
        mono = indata[:, 0].copy().astype(np.int16)
        audio_q.put(mono)
