import time
import json
import queue
import requests
import threading
import numpy as np
from openwakeword.model import Model
from .shared import audio_q, stop_flag, asr_flag

class WakeWordRunner:
    def __init__(self, cfg):
        import openwakeword
        openwakeword.utils.download_models()
        self.model = Model(wakeword_models=cfg["model_paths"], inference_framework="onnx")
        self.threshold = float(cfg['threshold'])
        self.cooldown_sec = float(cfg['cooldown_sec'])
        self.reset_sec = float(cfg['reset_sec'])
        self.url = cfg['url']

        self.last_trigger_time = 0.0
        self.last_activity_time = time.time()
        self.thread = threading.Thread(target=self.run)
        self.thread.start()
        print("WakeWordRunner start")

    def run(self):
        last_reset = time.time()
        frame_buffer = []  # 累积音频块

        while not stop_flag.is_set():
            if asr_flag.is_set():
                time.sleep(0.5)
                continue

            try:
                chunk = audio_q.get(timeout=0.5)            # int16 mono
            except queue.Empty:
                time.sleep(0.1)
                continue

            frame_buffer.append(chunk)
            if len(frame_buffer) >= 1:
                data = np.concatenate(frame_buffer)
                scores = self.model.predict(data)
                _, score = max(scores.items(), key=lambda kv: kv[1])
                now = time.time()
                frame_buffer = []  # 清空缓冲区

                if now - last_reset >= self.reset_sec:
                    self.model.reset()
                    last_reset = now

                if (now - self.last_trigger_time) < self.cooldown_sec:
                    continue

                if score >= self.threshold:
                    print(f"WordScores: {scores}")
                    asr_flag.set()
                    # try:
                    #     data_json = json.dump({"msg": "wakeup"})
                    #     requests.post(self.url, data=data_json)
                    #     self.last_trigger_time = now
                    # except Exception as e:
                    #     print("WakeWordRunner send request failed: ", e)