#!/usr/bin/env python3
"""
国家详尽报告 - 脚注标注与参考文献中文化工具

功能：
1. 为报告正文段落添加脚注序号标注（蓝色斜体）
2. 将参考文献英文标题翻译为中文
3. 验证脚注与参考文献的对应关系

用法：
  python footnote_tool.py --input input.docx --output output.docx --footnotes '{"8":"①②③"}'
  python footnote_tool.py --input input.docx --output output.docx --translate-refs
"""

import argparse
import json
import sys
from pathlib import Path

try:
    from docx import Document
    from docx.shared import Pt, RGBColor
except ImportError:
    print("ERROR: python-docx not installed. Run: pip install python-docx")
    sys.exit(1)


def add_footnote_markers(doc, footnote_map):
    """Add footnote markers at the end of specified paragraphs."""
    count = 0
    for idx_str, markers in footnote_map.items():
        idx = int(idx_str)
        if idx < len(doc.paragraphs):
            para = doc.paragraphs[idx]
            if para.text.strip():
                run = para.add_run(f' [{markers}]')
                run.font.size = Pt(9)
                run.font.color.rgb = RGBColor(0, 0, 180)
                run.font.italic = True
                count += 1
    return count


def translate_references(doc, translation_map):
    """Replace reference paragraph text with Chinese translations."""
    count = 0
    for idx_str, new_text in translation_map.items():
        idx = int(idx_str)
        if idx < len(doc.paragraphs):
            para = doc.paragraphs[idx]
            for run in para.runs:
                run.text = ''
            if para.runs:
                para.runs[0].text = new_text
            else:
                para.add_run(new_text)
            count += 1
    return count


def validate_footnotes(doc):
    """Validate footnote markers match reference list."""
    import re
    # Find all footnote markers in text
    markers_used = set()
    for para in doc.paragraphs:
        matches = re.findall(r'[①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳]', para.text)
        markers_used.update(matches)
    
    # Find all reference markers
    refs_defined = set()
    for para in doc.paragraphs:
        matches = re.findall(r'^[①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳]', para.text.strip())
        refs_defined.update(matches)
    
    # Check consistency
    used_not_defined = markers_used - refs_defined
    defined_not_used = refs_defined - markers_used
    
    result = {
        'markers_used': sorted(markers_used, key=lambda x: '①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳'.index(x)),
        'refs_defined': sorted(refs_defined, key=lambda x: '①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳'.index(x)),
        'used_not_defined': list(used_not_defined),
        'defined_not_used': list(defined_not_used),
        'valid': len(used_not_defined) == 0 and len(defined_not_used) == 0
    }
    return result


def main():
    parser = argparse.ArgumentParser(description='国家详尽报告脚注工具')
    parser.add_argument('--input', required=True, help='输入docx文件路径')
    parser.add_argument('--output', required=True, help='输出docx文件路径')
    parser.add_argument('--footnotes', help='脚注映射JSON, 如 {"8":"①②③"}')
    parser.add_argument('--translate-refs', help='参考文献翻译映射JSON, 如 {"175":"① 中文标题"}')
    parser.add_argument('--validate', action='store_true', help='验证脚注与参考文献对应关系')
    
    args = parser.parse_args()
    
    doc = Document(args.input)
    
    if args.footnotes:
        footnote_map = json.loads(args.footnotes)
        count = add_footnote_markers(doc, footnote_map)
        print(f'Added {count} footnote markers')
    
    if args.translate_refs:
        translation_map = json.loads(args.translate_refs)
        count = translate_references(doc, translation_map)
        print(f'Translated {count} references')
    
    if args.validate:
        result = validate_footnotes(doc)
        print(f'Validation result: {json.dumps(result, ensure_ascii=False, indent=2)}')
        if not result['valid']:
            if result['used_not_defined']:
                print(f'WARNING: Footnote markers used but not defined: {result["used_not_defined"]}')
            if result['defined_not_used']:
                print(f'WARNING: References defined but not used: {result["defined_not_used"]}')
    
    doc.save(args.output)
    print(f'Saved to: {args.output}')


if __name__ == '__main__':
    main()
