"""
voice_import.py — Voice2MD 管线 A：离线导入（原子组合器）

Spec 来源: docs/SPEC_voice2md_atomization_design.md §二
提取自: mindos_sse.py._runOssTranscribePipeline() 82 行 → 本文件 ~30 行编排

原子组合:
  ⑦ asr_batch   (flash_asr.transcribe_from_oss_url)
  ⑧ md_writer   (md_converter.MdConverter)
  ④ db_persist  (voice2md_atoms.persist_audio_result)
  ⑤ sse_push    (voice2md_atoms.push_md_appended)
  + 积分扣减    (voice2md_atoms.deduct_asr_credits)
"""

import json
import logging
import os

logger = logging.getLogger("voice_import")


async def run(
    *,
    sse_server,
    user_id: str,
    chat_id: str,
    read_url: str,
    oss_key: str,
    title: str,
) -> None:
    """离线音频文件 → Markdown。管线只做编排，不做逻辑。

    调用方: mindos_sse.py 的音频转写路由，通过 asyncio.create_task(voice_import.run(...))
    """
    from flash_asr import transcribe_from_oss_url      # type: ignore  ⑦ asr_batch
    from md_converter import MdConverter                # type: ignore  ⑧ md_writer
    from voice2md_atoms import (                        # type: ignore  ④⑤ 共享终点
        persist_audio_result, push_md_appended, deduct_asr_credits,
    )

    wiki_root = os.getenv("MINDOS_WIKI_DIR", os.path.expanduser("~/.hermes/wiki"))
    wiki_dir  = os.path.join(wiki_root, user_id)
    converter = MdConverter(wiki_dir)

    original_filename = oss_key.split("/")[-1]

    # 进度推送：开始
    sse_server._pushEvent(user_id, "md:progress", {
        "chatId": chat_id, "stage": "asr_start", "filename": original_filename,
    })

    # ⑧ md_writer: 创建文件
    md_file     = converter.new_file(title=title, source_filename=original_filename)
    total_chars = 0
    last_offset_ms = 0

    # ⑦ asr_batch: paraformer-v2 异步转写
    async for seg in transcribe_from_oss_url(read_url):
        if seg.get("text"):
            offset_ms = seg.get("begin_ms", 0)
            if offset_ms > last_offset_ms:
                last_offset_ms = offset_ms
            total_chars += converter.append_segment(
                md_file, seg["text"], offset_ms=offset_ms,
            )

    # ⑧ md_writer: 写结束标记
    converter.finalize(md_file, char_count=total_chars)
    rel_path = converter.relative_path(md_file)

    # 积分扣减
    audio_seconds = last_offset_ms / 1000.0
    asr_credits = max(1, int(audio_seconds))
    deduct_asr_credits(
        user_id=user_id, chat_id=chat_id, credits=asr_credits,
        tx_type="asr_file", model="paraformer-v2", seconds=audio_seconds,
    )

    # 读取完整 MD 内容
    md_content = ""
    try:
        md_content = md_file.read_text(encoding="utf-8")
    except Exception:
        pass

    # ④ db_persist
    persist_audio_result(
        chat_id=chat_id, user_id=user_id,
        file_name=title, md_path=rel_path,
        chars=total_chars, md_content=md_content,
        oss_read_url=read_url,
    )

    # ⑤ sse_push
    push_md_appended(
        sse_server=sse_server, user_id=user_id, chat_id=chat_id,
        file=rel_path, chars=total_chars, md_content=md_content,
        message=f"✅ 会议记录已入库：{md_file.name}（{total_chars} 字）",
    )
