# -*- coding: utf-8 -*-
"""
record_utils.py — 问题记录工具函数

从原 server.py 迁入的纯函数（入库辅助）：generate_record_id / build_md_filename
/ extract_keywords_from_text / categorize_text / build_markdown_content。

仅 generate_record_id 依赖 RECORDS_DIR（从 utils.paths 取），其余为纯函数。
"""

import re
from datetime import datetime

from utils.paths import RECORDS_DIR


def generate_record_id():
    """生成记录 ID：RC-YYYYMMDD-NNNN"""
    today = datetime.now().strftime('%Y%m%d')
    # 查找今天已有的记录数
    project_dir = RECORDS_DIR / "项目"
    if project_dir.exists():
        today_files = list(project_dir.glob(f"RC-{today}-*.md"))
        seq = len(today_files) + 1
    else:
        seq = 1
    return f"RC-{today}-{seq:03d}"


def build_md_filename(record_id, project_name, phenomenon):
    """构建 Markdown 文件名"""
    # 从 phenomenon 提取关键词
    keywords = extract_keywords_from_text(phenomenon)
    keyword_str = keywords[0] if keywords else "问题"
    # 清理文件名
    keyword_str = re.sub(r'[\\/:*?"<>|\r\n\t]', '', keyword_str)[:20]
    return f"{record_id}-{project_name}-{keyword_str}.md"


def extract_keywords_from_text(text):
    """从文本提取关键词"""
    if not text:
        return []
    text = text.lower()
    keywords = []
    tech_keywords = [
        "redis", "mysql", "nacos", "emqx", "mqtt", "docker",
        "nginx", "java", "python", "smc", "exchange",
        "门口屏", "无纸化", "桌牌", "人脸", "签到", "白名单",
        "wss", "websocket", "授权", "激活", "token", "证书",
        "时区", "ntp", "磁盘", "内存", "oom",
        "配置", "config", "短信", "邮件", "同步",
        "钉钉", "企业微信", "welink", "oa",
        "连接失败", "启动失败", "未授权", "绑定失败",
    ]
    for kw in tech_keywords:
        if kw in text:
            keywords.append(kw)
    return keywords[:3]


def categorize_text(text):
    """自动分类"""
    if not text:
        return ["其他"]
    text = text.lower()
    categories = []
    rules = {
        "服务/容器异常": ["docker", "容器", "服务", "500", "502", "启动失败", "exited"],
        "设备终端-门口屏": ["门口屏", "门ロ屏"],
        "设备终端-无纸化": ["无纸化"],
        "设备终端-桌牌": ["桌牌"],
        "MQTT/EMQX": ["mqtt", "emqx", "wss", "websocket"],
        "数据库": ["mysql", "redis", "数据库", "连接失败"],
        "配置文件": ["配置", "config", "不生效"],
        "前端/UI": ["页面", "前端", "ui", "显示"],
        "部署/升级": ["部署", "升级", "更新"],
        "网络/SSH": ["网络", "ssh", "端口", "不通"],
        "授权/激活": ["授权", "激活", "token", "jwt", "证书"],
    }
    for cat, kws in rules.items():
        for kw in kws:
            if kw in text:
                categories.append(cat)
                break
    return categories if categories else ["其他"]


def build_markdown_content(record_id, project_name, system_type, apk_product,
                           phenomenon, troubleshoot_steps, root_cause, solution, recorder):
    """构建 Markdown 内容"""
    today = datetime.now().strftime('%Y-%m-%d')
    categories = categorize_text(phenomenon + " " + (root_cause or ""))
    keywords = extract_keywords_from_text(phenomenon + " " + (root_cause or "") + " " + (solution or ""))

    lines = []
    # Frontmatter
    lines.append("---")
    lines.append(f'id: "{record_id}"')
    lines.append(f'date: "{today}"')
    lines.append(f'source: "项目"')
    lines.append(f'project: "{project_name}"')
    lines.append(f'category: [{", ".join(categories)}]')
    lines.append(f'status: "未解决"')
    lines.append(f'keywords: [{", ".join(keywords)}]')
    lines.append(f'recorder: "{recorder}"')
    lines.append("---")
    lines.append("")

    # 标题
    lines.append(f"# [{project_name}] {phenomenon}")
    lines.append("")

    # 现象
    lines.append("## 现象")
    lines.append(phenomenon)
    lines.append("")

    # 系统类型和 APK 产品（如有）
    if system_type:
        lines.append(f"**系统类型**：{system_type}")
    if apk_product:
        lines.append(f"**APK 产品**：{apk_product}")
    if system_type or apk_product:
        lines.append("")

    # 排查过程
    if troubleshoot_steps:
        lines.append("## 排查过程")
        lines.append(troubleshoot_steps)
        lines.append("")

    # 根因
    if root_cause:
        lines.append("## 根因")
        lines.append(root_cause)
        lines.append("")

    # 解决方案
    if solution:
        lines.append("## 解决方案")
        lines.append(solution)
        lines.append("")

    # 元信息
    lines.append("## 元信息")
    lines.append(f"- 记录人：{recorder}")
    lines.append(f"- 记录时间：{today}")

    return "\n".join(lines)
