"""
voice2md_atoms.py — Voice2MD 共享原子层

Spec 来源: docs/SPEC_voice2md_atomization_design.md §九
提取自: mindos_sse.py._runOssTranscribePipeline (管线A)
        dashscope_realtime._finalize (管线B)

共享原子:
  ④ persist_audio_result()  — 统一 DB 持久化
  ⑤ push_md_appended()      — 统一 SSE 推送
"""

import json
import logging

logger = logging.getLogger("voice2md_atoms")


# ─── ④ db_persist: 统一音频结果持久化 ─────────────────────────

def persist_audio_result(
    chat_id: str,
    user_id: str,
    file_name: str,
    md_path: str,
    chars: int,
    md_content: str,
    oss_read_url: str = "",
) -> None:
    """将音频转写结果写入 SessionDB。

    管线 A (Import) 和管线 B (Live) 共用此函数。
    payload 结构统一为 {type:"audio", fileName, mdPath, chars, ossReadUrl, mdContent}。

    Raises:
        不抛出异常。失败仅 logger.warning。
    """
    try:
        from hermes_state import SessionDB  # type: ignore
        db = SessionDB()
        db.create_session(
            session_id=chat_id, source="mindos",
            user_id=user_id, model="audio",
        )
        db.append_message(
            session_id=chat_id,
            role="assistant",
            content=json.dumps({
                "type":       "audio",
                "fileName":   file_name,
                "mdPath":     md_path,
                "chars":      chars,
                "ossReadUrl": oss_read_url,
                "mdContent":  md_content,
            }, ensure_ascii=False),
        )
        logger.info("[voice2md] DB persist ok chatId=%s chars=%d", chat_id, chars)
    except Exception as e:
        logger.warning("[voice2md] DB persist failed (non-fatal): %s", e)


# ─── ⑤ sse_push: 统一 SSE md:appended 推送 ──────────────────

def push_md_appended(
    sse_server,
    user_id: str,
    chat_id: str,
    file: str,
    chars: int,
    md_content: str,
    message: str = "",
    source: str = "mic",
) -> None:
    """推送 SSE md:appended 事件到前端。

    管线 A 和管线 B 共用此函数。
    chars=0 时跳过推送（无内容不扰前端）。

    Args:
        sse_server: MindOSSSEServer 实例（具有 _pushEvent 方法）。
                    管线 A 传 self，管线 B 传 _sse_server 模块级变量。
        source: 音频来源标识（"mic" 或 "system"），前端据此区分气泡类型。
    """
    if chars == 0:
        logger.info("[voice2md] 无转写内容，跳过 SSE 推送 chatId=%s", chat_id)
        return

    if not sse_server:
        logger.warning("[voice2md] SSE push 跳过: sse_server 未注入")
        return

    if not message:
        message = f"✅ 转写完成（{chars} 字）"

    try:
        sse_server._pushEvent(user_id, "md:appended", {
            "chatId":    chat_id,
            "file":      file,
            "chars":     chars,
            "mdContent": md_content,
            "message":   message,
            "source":    source,
        })
        logger.info("[voice2md] SSE md:appended pushed userId=%s chars=%d source=%s", user_id, chars, source)
    except Exception as e:
        logger.warning("[voice2md] SSE push failed: %s", e)


# ─── ASR 积分扣减（管线 A/B 各自计费方式不同，不统一） ─────────

def deduct_asr_credits(
    user_id: str,
    chat_id: str,
    credits: int,
    tx_type: str,
    model: str,
    seconds: float,
) -> None:
    """ASR 积分扣减。管线 A 和 B 调用时传不同的 tx_type 和 model。"""
    try:
        from hermes_state import SessionDB  # type: ignore
        db = SessionDB()
        db.deduct_credits(
            user_id=user_id,
            credits=credits,
            tx_type=tx_type,
            session_id=chat_id,
            model=model,
            raw_metric=json.dumps({"seconds": round(seconds, 1)}),
        )
        logger.info(
            "[ASR Cost] userId=%s model=%s type=%s seconds=%.1f credits=%d chatId=%s",
            user_id, model, tx_type, seconds, credits, chat_id,
        )
    except Exception as e:
        logger.warning("[voice2md] credit deduction failed: %s", e)
