# -*- coding: utf-8 -*-
"""
build_index.py — 问题知识库索引生成工具

功能：
  扫描问题记录 Markdown 文件，生成：
  1. 索引.md — 可读的分类索引
  2. 搜索索引.json — 供 search_engine.py 使用的结构化索引

用法：
  python build_index.py
"""

import os
import re
import json
from pathlib import Path
from datetime import datetime
from collections import defaultdict

# ============================================================
# 配置
# ============================================================

SCRIPT_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = SCRIPT_DIR.parent.parent.parent.parent

DATA_DIR = PROJECT_ROOT / "Docs" / "PRD" / "问题知识库"
RECORDS_DIR = DATA_DIR / "问题记录"
INDEX_FILE = DATA_DIR / "索引.md"
SEARCH_INDEX_FILE = DATA_DIR / "搜索索引.json"


def parse_frontmatter(content):
    """解析 Markdown 文件的 frontmatter"""
    fm = {}
    match = re.match(r'^---\n(.*?)\n---', content, re.DOTALL)
    if not match:
        return fm

    fm_text = match.group(1)
    for line in fm_text.split('\n'):
        if ':' not in line:
            continue
        key, value = line.split(':', 1)
        key = key.strip()
        value = value.strip()

        # 处理列表格式 [a, b, c]
        if value.startswith('[') and value.endswith(']'):
            items = value[1:-1].split(',')
            fm[key] = [i.strip().strip('"\'') for i in items if i.strip()]
        # 处理字符串格式 "xxx"
        elif value.startswith('"') and value.endswith('"'):
            fm[key] = value[1:-1]
        elif value.startswith("'") and value.endswith("'"):
            fm[key] = value[1:-1]
        else:
            fm[key] = value

    return fm


def extract_content(content):
    """提取 Markdown 正文内容（去除 frontmatter）"""
    # 去除 frontmatter
    content = re.sub(r'^---\n.*?\n---\n*', '', content, flags=re.DOTALL)
    return content.strip()


def scan_records():
    """扫描所有问题记录文件"""
    records = []

    for subdir in ['日常', '项目', '归档']:
        dir_path = RECORDS_DIR / subdir
        if not dir_path.exists():
            continue

        for md_file in dir_path.glob('*.md'):
            try:
                content = md_file.read_text(encoding='utf-8')
                fm = parse_frontmatter(content)
                body = extract_content(content)

                # 提取现象（第一个 # 标题后的内容）
                phenomenon = ""
                phen_match = re.search(r'^#\s+(.+)$', body, re.MULTILINE)
                if phen_match:
                    phenomenon = phen_match.group(1)

                # 构建 full_text 用于搜索
                full_text = body.lower()

                record = {
                    'id': fm.get('id', ''),
                    'file': f"问题记录/{subdir}/{md_file.name}",
                    'title': phenomenon or md_file.stem,
                    'phenomenon': phenomenon,
                    'project': fm.get('project', ''),
                    'source': subdir,
                    'status': fm.get('status', '未知'),
                    'category': fm.get('category', []),
                    'keywords': fm.get('keywords', []),
                    'recorder': fm.get('recorder', ''),
                    'responsible': fm.get('responsible', ''),
                    'date': fm.get('date', ''),
                    'full_text': full_text,
                }
                records.append(record)
            except Exception as e:
                print(f"⚠️  解析文件失败：{md_file.name} - {e}")

    return records


def build_search_index(records):
    """构建搜索索引（JSON 格式）"""
    # 按分类建立索引
    categories = defaultdict(list)
    for i, r in enumerate(records):
        for cat in r.get('category', []):
            categories[cat].append(i)

    # 按项目建立索引
    projects = defaultdict(list)
    for i, r in enumerate(records):
        proj = r.get('project', '')
        if proj:
            projects[proj].append(i)

    # 按状态建立索引
    statuses = defaultdict(list)
    for i, r in enumerate(records):
        status = r.get('status', '未知')
        statuses[status].append(i)

    # 提取所有项目名称（用于前端下拉建议）
    project_names = sorted(set(r.get('project', '') for r in records if r.get('project')))

    index = {
        'last_update': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'total': len(records),
        'records': records,
        'categories': dict(categories),
        'projects': dict(projects),
        'project_names': project_names,
        'statuses': dict(statuses),
        'stats': {
            '已解决': len(statuses.get('已解决', [])),
            '未解决': len(statuses.get('未解决', [])),
            '未知': len(statuses.get('未知', [])),
        }
    }

    return index


def build_markdown_index(records):
    """生成可读的 Markdown 索引"""
    lines = []
    lines.append("# 问题知识库索引")
    lines.append("")
    lines.append(f"> 最后更新：{datetime.now().strftime('%Y-%m-%d %H:%M')}")
    lines.append(f"> 总记录数：{len(records)} 条")
    lines.append("")

    # 统计
    stats = defaultdict(int)
    for r in records:
        stats[r.get('status', '未知')] += 1
    lines.append(f"> 已解决：{stats.get('已解决', 0)} 条 | 未解决：{stats.get('未解决', 0)} 条 | 未知：{stats.get('未知', 0)} 条")
    lines.append("")
    lines.append("---")
    lines.append("")

    # 按分类浏览
    lines.append("## 按分类浏览")
    lines.append("")

    category_records = defaultdict(list)
    for r in records:
        for cat in r.get('category', []):
            category_records[cat].append(r)

    for cat in sorted(category_records.keys()):
        recs = category_records[cat]
        lines.append(f"### {cat} ({len(recs)} 条)")
        for r in recs[:10]:  # 每类最多显示 10 条
            status_icon = "✅" if r.get('status') == '已解决' else "⏳"
            proj = f"[{r.get('project')}]" if r.get('project') else ""
            lines.append(f"- {status_icon} [{proj}{r.get('title', '未知')}](./{r.get('file')})")
        if len(recs) > 10:
            lines.append(f"  - ... 还有 {len(recs) - 10} 条")
        lines.append("")

    # 按项目浏览
    lines.append("## 按项目浏览")
    lines.append("")

    project_records = defaultdict(list)
    for r in records:
        proj = r.get('project', '')
        if proj:
            project_records[proj].append(r)

    for proj in sorted(project_records.keys()):
        recs = project_records[proj]
        lines.append(f"### {proj} ({len(recs)} 条)")
        for r in recs[:10]:
            status_icon = "✅" if r.get('status') == '已解决' else "⏳"
            lines.append(f"- {status_icon} [{r.get('title', '未知')}](./{r.get('file')})")
        if len(recs) > 10:
            lines.append(f"  - ... 还有 {len(recs) - 10} 条")
        lines.append("")

    # 未解决问题列表
    unresolved = [r for r in records if r.get('status') not in ('已解决', '已关闭')]
    if unresolved:
        lines.append("## 未解决问题")
        lines.append("")
        for r in unresolved[:20]:
            proj = f"[{r.get('project')}] " if r.get('project') else ""
            lines.append(f"- [ ] {proj}{r.get('title', '未知')}")
        if len(unresolved) > 20:
            lines.append(f"- ... 还有 {len(unresolved) - 20} 条未解决")
        lines.append("")

    return "\n".join(lines)


def main():
    """主函数"""
    if hasattr(__import__('sys').stdout, 'reconfigure'):
        __import__('sys').stdout.reconfigure(encoding='utf-8')

    print("📂 扫描问题记录...")
    records = scan_records()
    print(f"   找到 {len(records)} 条记录")

    if not records:
        print("❌ 未找到任何记录")
        return

    # 生成搜索索引
    print("🔍 生成搜索索引...")
    search_index = build_search_index(records)
    SEARCH_INDEX_FILE.write_text(json.dumps(search_index, ensure_ascii=False, indent=2), encoding='utf-8')
    print(f"   ✅ {SEARCH_INDEX_FILE}")

    # 生成 Markdown 索引
    print("📝 生成 Markdown 索引...")
    md_index = build_markdown_index(records)
    INDEX_FILE.write_text(md_index, encoding='utf-8')
    print(f"   ✅ {INDEX_FILE}")

    # 输出统计
    print(f"\n📊 统计：")
    print(f"   总记录：{len(records)} 条")
    print(f"   分类数：{len(search_index['categories'])} 个")
    print(f"   项目数：{len(search_index['project_names'])} 个")
    print(f"   已解决：{search_index['stats']['已解决']} 条")
    print(f"   未解决：{search_index['stats']['未解决']} 条")

    print(f"\n🎉 索引生成完成！")


if __name__ == "__main__":
    main()