from datetime import datetime
from fastapi import FastAPI
from pydantic import BaseModel
from loguru import logger

app = FastAPI(title="直播状态控制接口")
app.shared_config = None

class SpeakingStatus(BaseModel):
    is_speaking: bool

@app.post("/speaking-status", summary="更新说话状态")
def update_speaking_status(status: SpeakingStatus):
    if app.shared_config is None:
        return {"error": "服务未初始化"}

    prev = app.shared_config.get("is_speaking", False)
    app.shared_config["is_speaking"] = status.is_speaking

    # 当状态从 True 变为 False 的瞬间，取出预测队列并计算差值
    if (not status.is_speaking) and prev:
        now_dt = datetime.now()
        now_str = now_dt.strftime("%Y-%m-%d %H:%M:%S")
        app.shared_config["speaking_false_time"] = now_str

        predicted_time_str = None
        try:
            q = app.shared_config.get("prediction_queue")
            if q is not None and len(q) > 0:
                predicted_time_str = q.pop(0)
        except Exception:
            predicted_time_str = None

        app.shared_config["predicted_time"] = predicted_time_str

        # 打印日志
        if predicted_time_str:
            try:
                predicted_dt = datetime.strptime(predicted_time_str, "%Y-%m-%d %H:%M:%S")
                delta_seconds = (now_dt - predicted_dt).total_seconds()
                app.shared_config["time_diff_seconds"] = float(delta_seconds)
                logger.info(
                    f"[计算差值] 队列剩余: {list(app.shared_config.get('prediction_queue', []))} | "
                    f"真实时间: {now_str} | 使用预测: {predicted_time_str} | 差值(秒): {delta_seconds}"
                )
            except Exception:
                app.shared_config["time_diff_seconds"] = None
        else:
            app.shared_config["time_diff_seconds"] = None
            logger.warning(
                f"[计算差值] 队列为空或解析失败 | 真实时间: {now_str}"
            )

    return {"message": "状态更新成功"}
