"""
PDF 章节提取命令行工具 - 简化版

使用方法:
    python extract_cli.py <pdf文件路径> [options]

示例:
    python extract_cli.py document.pdf
    python extract_cli.py document.pdf -e "第一章" "第二章" "第三章"
    python extract_cli.py document.pdf -o ./output -v
"""

from __future__ import annotations

import argparse
import json
import sys
from datetime import datetime
from pathlib import Path

# 添加项目路径
def setup_path():
    current_file = Path(__file__).resolve()
    project_root = current_file.parent.parent.parent.parent
    if str(project_root) not in sys.path:
        sys.path.insert(0, str(project_root))

setup_path()

from foundation.observability.logger.loggering import review_logger as logger
from core.construction_review.component.doc_worker.pdf_worker import (
    PdfTextSplitter, PdfFullTextExtractor, HybridFullTextExtractor, OcrEnhancedExtractor
)
from core.construction_review.component.doc_worker.interfaces import DocumentSource


def main():
    parser = argparse.ArgumentParser(
        description="PDF章节提取工具（简化版）",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
章节标题匹配规则:
  章标题: 第[中文数字]+章 (如: 第一章 编制依据)
  节标题: [中文数字]+、 (如: 一、项目概况)

提取模式:
  本地模式: 仅 PyMuPDF 提取（默认，章节切分最稳定）
  OCR enhanced: PyMuPDF 提取 + 表格页 OCR 替换（推荐，平衡稳定与效果）
  OCR hybrid: 表格页直接 OCR（速度快但可能破坏章节格式）

示例:
  python extract_cli.py document.pdf
  python extract_cli.py document.pdf --ocr                    # 启用 OCR (默认 enhanced)
  python extract_cli.py document.pdf --ocr --ocr-mode hybrid  # 使用 hybrid 模式
  python extract_cli.py document.pdf -e "第一章" "第二章"
  python extract_cli.py document.pdf -o ./output --no-validation
        """
    )

    parser.add_argument(
        "pdf_path",
        help="PDF文件路径"
    )

    parser.add_argument(
        "-e", "--expected",
        nargs="+",
        help="期望的章节列表（用于检查缺失）"
    )

    parser.add_argument(
        "-o", "--output",
        help="输出目录（默认为PDF所在目录）"
    )

    parser.add_argument(
        "--no-validation",
        action="store_true",
        help="禁用章节验证"
    )

    parser.add_argument(
        "-v", "--verbose",
        action="store_true",
        help="输出详细信息"
    )

    parser.add_argument(
        "--ocr",
        action="store_true",
        help="启用 OCR 模式（表格页使用 OCR 识别）"
    )

    parser.add_argument(
        "--ocr-mode",
        choices=["enhanced", "hybrid"],
        default="enhanced",
        help="OCR 模式: enhanced (推荐，稳定) 或 hybrid (表格页直接OCR)"
    )

    args = parser.parse_args()

    # 检查文件
    pdf_file = Path(args.pdf_path)
    if not pdf_file.exists():
        print(f"[错误] 文件不存在: {args.pdf_path}")
        sys.exit(1)

    # 确定输出目录
    if args.output:
        output_dir = Path(args.output)
        output_dir.mkdir(parents=True, exist_ok=True)
    else:
        output_dir = pdf_file.parent

    # 确定模式显示文本
    if args.ocr:
        mode_text = f"OCR {args.ocr_mode} (表格页识别)"
    else:
        mode_text = "本地提取 (PyMuPDF)"

    print(f"\n{'='*60}")
    print(f"PDF章节提取")
    print(f"{'='*60}")
    print(f"文件: {pdf_file.name}")
    print(f"输出: {output_dir}")
    print(f"验证: {'禁用' if args.no_validation else '启用'}")
    print(f"模式: {mode_text}")
    print(f"{'='*60}\n")

    try:
        # 1. 提取全文
        print("[1/3] 提取PDF文本...")
        if args.ocr:
            if args.ocr_mode == "enhanced":
                extractor = OcrEnhancedExtractor()
                print("      使用 OCR enhanced 模式（PyMuPDF + 表格页 OCR 替换）")
            else:
                extractor = HybridFullTextExtractor()
                print("      使用 OCR hybrid 模式（表格页直接 OCR）")
        else:
            extractor = PdfFullTextExtractor()
            print("      使用本地提取模式")
        source = DocumentSource(path=pdf_file)
        pages_content = extractor.extract_full_text(source)
        print(f"      共 {len(pages_content)} 页")

        # 2. 切分章节
        print("\n[2/3] 章节切分...")
        splitter = PdfTextSplitter(
            enable_validation=not args.no_validation,
            expected_chapters=args.expected or []
        )

        chunks = splitter.split_by_hierarchy(
            classification_items=[],
            pages_content=pages_content,
            toc_info={},
            target_level=1,
            max_chunk_size=10000,
            min_chunk_size=10,
        )
        print(f"      生成 {len(chunks)} 个内容块")

        # 3. 构建结构化数据
        structured_data = {}
        for chunk in chunks:
            chapter = chunk.get("_chapter_title", "未分类")
            section = chunk.get("_section_title", "默认")
            content = chunk.get("review_chunk_content", "")

            if chapter not in structured_data:
                structured_data[chapter] = {}
            structured_data[chapter][section] = content

        # 4. 获取验证报告（传入结构化数据以构建大纲）
        print("\n[3/3] 生成报告...")
        report = splitter.get_validation_report(structured_data)

        # 5. 保存结果
        current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
        output_file = output_dir / f"{pdf_file.stem}_extracted_{current_time}.json"

        result = {
            "metadata": {
                "source_file": str(pdf_file),
                "total_pages": len(pages_content),
                "chunk_count": len(chunks),
                "extraction_time": current_time,
            },
            "outline": report.get("outline", []),  # 新增：大纲
            "validation_report": report,
            "structured_data": structured_data,
        }

        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(result, f, ensure_ascii=False, indent=2)

        # 6. 输出大纲和验证报告
        if not args.no_validation:
            # 显示大纲
            print("\n" + "-"*60)
            print("文档大纲")
            print("-"*60)

            outline = report.get("outline", [])
            for chapter in outline:
                status = "✓" if chapter.get("is_valid") else "✗"
                section_info = f" ({chapter.get('section_count', 0)}节)"
                print(f"\n{status} {chapter['title']}{section_info}")

                for section in chapter.get("children", []):
                    sec_status = "✓" if section.get("is_valid") else "✗"
                    content_len = section.get("content_length", 0)
                    print(f"    {sec_status} {section['title']} [{content_len}字符]")

            # 显示统计
            print("\n" + "-"*60)
            print("章节规范检查")
            print("-"*60)

            summary = report.get("summary", {})
            print(f"\n总计: {summary.get('total', 0)} 个章节")
            print(f"  规范: {summary.get('valid', 0)}")
            print(f"  异常: {summary.get('invalid', 0)}")

            # 显示异常章节
            invalid_results = [r for r in report.get("results", []) if not r.get("is_valid")]
            if invalid_results:
                print(f"\n⚠ 异常章节:")
                for r in invalid_results:
                    print(f"\n  ✗ {r['chapter']}")
                    for issue in r.get("issues", []):
                        print(f"    ! {issue}")

            # 显示警告
            warnings = report.get("warnings", [])
            if warnings:
                print(f"\n⚠ 警告:")
                for w in warnings[:5]:
                    print(f"  ! {w}")

        print("\n" + "="*60)
        print(f"✓ 提取完成: {output_file}")
        print(f"="*60)

        # 返回码
        invalid_count = report.get("summary", {}).get("invalid", 0)
        if invalid_count > 0:
            print(f"\n注意: 发现 {invalid_count} 个异常章节")
            sys.exit(1)

    except Exception as e:
        print(f"\n[错误] {e}")
        import traceback
        traceback.print_exc()
        sys.exit(2)


if __name__ == "__main__":
    main()
