#!/usr/bin/env python3
"""
细纲核对工具 v1.0
朝暮 ICE-GL-CM001 · 明天见频道 · novel-system

功能：逐章比对正文与细纲，检测：
  - 剧情点覆盖率（细纲中的关键事件在正文中是否体现）
  - 设定矛盾（数值链条、状态变化）
  - 衔接连贯性

用法: python3 细纲核对.py <正文目录> <细纲文件.md>
"""

import sys, os, re

def read_chapters(path):
    """读取章节正文，返回 [(标题, 正文文本), ...]"""
    chapters = []
    txt_files = sorted([f for f in os.listdir(path) if f.endswith('.txt')])

    for fname in txt_files:
        fpath = os.path.join(path, fname)
        with open(fpath, 'r', encoding='utf-8') as f:
            content = f.read()

        lines = [l.strip() for l in content.split('\n') if l.strip()]
        current_ch, current_lines = None, []

        for line in lines:
            if re.match(r'第[零一二三四五六七八九十百千\d]+章', line) and len(line) < 25:
                if current_ch:
                    chapters.append((current_ch, '\n'.join(current_lines)))
                current_ch, current_lines = line, []
            else:
                current_lines.append(line)

        if current_ch:
            chapters.append((current_ch, '\n'.join(current_lines)))

    return chapters

def parse_outline(outline_path):
    """解析细纲文件，提取每章的@lock和@scene"""
    with open(outline_path, 'r', encoding='utf-8') as f:
        content = f.read()

    outline_chapters = []
    # 按 ## 第X章 分割
    sections = re.split(r'(## 第\d+章)', content)

    current_title = None
    for i, section in enumerate(sections):
        if section.startswith('## 第'):
            current_title = section.strip('# ')
        elif current_title:
            # 提取关键信息
            lock_match = re.search(r'@lock:\s*(.+?)(?:\n|$)', section)
            scene_match = re.search(r'@scene:\s*(.+?)(?:\n|$)', section)
            trigger_match = re.search(r'@trigger:\s*(.+?)(?:\n|$)', section)
            emergence_match = re.search(r'@emergence:\s*(.+?)(?:\n|$)', section)

            outline_chapters.append({
                'title': current_title,
                'lock': lock_match.group(1).strip() if lock_match else '',
                'scene': scene_match.group(1).strip() if scene_match else '',
                'trigger': trigger_match.group(1).strip() if trigger_match else '',
                'emergence': emergence_match.group(1).strip() if emergence_match else '',
            })
            current_title = None

    return outline_chapters

def check_outline_coverage(chapter_text, outline_entry):
    """检查正文是否覆盖了细纲的关键事件"""
    issues = []

    # 检查 @scene 中的关键意象/事件
    if outline_entry.get('scene'):
        scene_items = outline_entry['scene'].split('/')
        for item in scene_items:
            item = item.strip()
            if not item or len(item) < 10:
                continue
            # 提取核心词（取前5个字作为搜索关键词）
            keywords = item[:15]
            if keywords not in chapter_text:
                issues.append(f"细纲场景未体现: {item[:40]}...")

    # 检查 @lock 中的数值要求
    if outline_entry.get('lock'):
        lock_items = outline_entry['lock'].split('/')
        for item in lock_items:
            item = item.strip()
            if '→' in item:
                # 数值变化，如 "灰芽60%→61%"
                target = item.split('→')[-1].strip()
                # 提取数值部分
                num_match = re.search(r'[\d.]+%?万?', target)
                if num_match:
                    target_num = num_match.group()
                    if target_num not in chapter_text:
                        issues.append(f"数值目标未体现: {item.strip()}")

    return issues

def main():
    if len(sys.argv) < 3:
        print("用法: python3 细纲核对.py <正文目录> <细纲文件.md>")
        sys.exit(1)

    chapters_dir = sys.argv[1]
    outline_file = sys.argv[2]

    if not os.path.isdir(chapters_dir):
        print(f"错误: '{chapters_dir}' 不是有效目录")
        sys.exit(1)
    if not os.path.isfile(outline_file):
        print(f"错误: '{outline_file}' 不是有效文件")
        sys.exit(1)

    chapters = read_chapters(chapters_dir)
    outline = parse_outline(outline_file)

    print("═" * 60)
    print(f"细纲核对报告")
    print(f"正文: {len(chapters)} 章 | 细纲: {len(outline)} 条")
    print("═" * 60)
    print()

    total_issues = 0

    for ch_title, ch_text in chapters:
        # 匹配对应的细纲条目
        ch_num_match = re.search(r'第(\d+)章', ch_title)
        if not ch_num_match:
            continue
        ch_num = int(ch_num_match.group(1))

        outline_entry = None
        for o in outline:
            o_num_match = re.search(r'第(\d+)章', o['title'])
            if o_num_match and int(o_num_match.group(1)) == ch_num:
                outline_entry = o
                break

        if not outline_entry:
            print(f"⚠️ {ch_title}: 未找到对应细纲")
            total_issues += 1
            continue

        issues = check_outline_coverage(ch_text, outline_entry)

        if issues:
            print(f"🔶 {ch_title}:")
            for issue in issues:
                print(f"   - {issue}")
            total_issues += len(issues)
            print()
        else:
            print(f"✅ {ch_title}: 细纲核对通过")
            print()

    print("═" * 60)
    if total_issues == 0:
        print("✅ 所有章节细纲核对通过！")
    else:
        print(f"共发现 {total_issues} 个核对问题")
    print("═" * 60)

if __name__ == '__main__':
    main()
