import queue
import torch
from TTS.api import TTS  # type: ignore
import whisper
from flask_socketio import SocketIO
from app.database.fetch_data import get_mongo_client

# 1️⃣ The single SocketIO instance
socketio = SocketIO(cors_allowed_origins="*", async_mode="eventlet")

# 2️⃣ Any global/shared session-state dicts
audio_buffers     = {}
characterIds      = {}
sectionIds        = {}
last_ping_time    = {}
buttonsStates     = {}
character_actions = {}
distance_objects  = {}
action_modes      = {}
metadata          = {}

# 2️⃣ The global client for MongoDB
# 3️⃣ Your model pools
use_gpu = torch.cuda.is_available()
client= get_mongo_client()
device = "cuda" if torch.cuda.is_available() else "cpu"
TTS_INSTANCES = [TTS(model_name="tts_models/en/ljspeech/fast_pitch", progress_bar=False).to(device) for _ in range(2)]
STT_INSTANCES = [whisper.load_model("base").to(device) for _ in range(2)]
tts_queue = queue.Queue(); stt_queue = queue.Queue()
for i in range(len(TTS_INSTANCES)): tts_queue.put(i)
for i in range(len(STT_INSTANCES)): stt_queue.put(i)

CHUNK_SIZE = 4096

def get_available_tts(): return tts_queue.get(block=True)
def get_available_stt(): return stt_queue.get(block=True)
def release_tts(idx): tts_queue.put(idx)
def release_stt(idx): stt_queue.put(idx)