"""
MindOS NEXT — mdConverter：transcript 片段 → Markdown 文件追加

封闭函数（铁律 1）：
  输入：transcript 文本片段（str）+ 可选毫秒偏移（int）
  输出：追加到 wiki/meetings/*.md
  副作用：仅磁盘文件写入；不调用 LLM，不写 DB。

MD-First（铁律 6）：
  音频/文件的唯一持久化形式就是这个 .md 文件。
  无 DB 记录，无 UUID，文件名即身份。
"""

import os
import time
import threading
from datetime import datetime
from pathlib import Path
from typing import Optional


_MIME_TO_EXT = {
    "audio/mpeg": "mp3", "audio/mp4": "m4a", "audio/mp3": "mp3",
    "audio/wav": "wav", "audio/webm": "webm", "audio/ogg": "ogg",
    "audio/aac": "aac", "audio/flac": "flac",
}

_SUPPORTED_EXTS = {".mp3", ".mp4", ".m4a", ".wav", ".webm", ".ogg", ".aac", ".flac"}


def is_supported_audio(filename: str) -> bool:
    return Path(filename).suffix.lower() in _SUPPORTED_EXTS


class MdConverter:
    """transcript 片段追加为 Markdown 文件（L0 原文层）。"""

    def __init__(self, wiki_dir: str):
        self.meetings_dir = Path(wiki_dir) / "raw"
        self.meetings_dir.mkdir(parents=True, exist_ok=True)
        self._lock = threading.Lock()

    def new_file(
        self,
        title: str = "未命名",
        source_filename: str = "",
        duration_hint: str = "",
    ) -> Path:
        """
        创建新 MD 文件，写入 YAML-style header，返回文件路径。
        文件名：YYYY-MM-DD_HHmm_<title>.md
        """
        now = datetime.now()
        safe_title = title.replace("/", "-").replace("\\", "-")[:20]
        filename = f"{now.strftime('%Y-%m-%d_%H%M')}_{safe_title}.md"
        file_path = self.meetings_dir / filename

        source_line = f"来源：`{source_filename}` | " if source_filename else ""
        duration_line = f"时长：{duration_hint} | " if duration_hint else ""

        header = (
            f"# {now.strftime('%Y-%m-%d %H:%M')} {title}\n\n"
            f"> {source_line}{duration_line}"
            f"转写模型：qwen3-asr-flash | 入库时间：{now.strftime('%Y-%m-%d %H:%M')}\n\n"
            f"---\n\n"
        )
        with self._lock:
            file_path.write_text(header, encoding="utf-8")

        return file_path

    def append_segment(
        self,
        file_path: Path,
        text: str,
        offset_ms: int = 0,
    ) -> int:
        """
        追加一个 transcript 片段。
        格式：[MM:SS] 文字内容
        返回追加的字符数。
        """
        text = text.strip()
        if not text:
            return 0

        if offset_ms > 0:
            total_s = offset_ms // 1000
            mm, ss = divmod(total_s, 60)
            timestamp = f"[{mm:02d}:{ss:02d}] "
        else:
            timestamp = ""

        line = f"{timestamp}{text}\n\n"
        with self._lock:
            with file_path.open("a", encoding="utf-8") as f:
                f.write(line)

        return len(text)

    def finalize(self, file_path: Path, char_count: int = 0) -> None:
        """写入结束标记。"""
        summary = f"\n---\n\n> ✅ 转写完成，共 {char_count} 字\n"
        with self._lock:
            with file_path.open("a", encoding="utf-8") as f:
                f.write(summary)

    def relative_path(self, file_path: Path) -> str:
        """返回相对于 meetings_dir 父目录的路径，用于日志/SSE。"""
        try:
            return str(file_path.relative_to(self.meetings_dir.parent))
        except ValueError:
            return str(file_path)
