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

基于正则表达式的简单章节提取，支持章节规范检查。

使用方法:
    python simple_extract_cli.py <pdf文件路径>

输出:
    - JSON 文件：提取的结构化数据
    - 控制台：章节规范检查报告
"""

from __future__ import annotations

import argparse
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional

import fitz

# 添加项目路径
def setup_path():
    current_file = Path(__file__).resolve()
    project_root = current_file.parent.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.simple_splitter import (
    SimplePdfTextSplitter,
)


def extract_and_validate(
    pdf_path: str,
    expected_chapters: Optional[List[str]] = None,
    output_dir: Optional[str] = None,
    verbose: bool = True
) -> Dict[str, Any]:
    """
    提取PDF章节并进行规范验证

    Args:
        pdf_path: PDF文件路径
        expected_chapters: 期望的章节列表（用于检查缺失）
        output_dir: 输出目录，默认为PDF所在目录
        verbose: 是否输出详细日志

    Returns:
        包含提取结果和验证报告的字典
    """
    pdf_file = Path(pdf_path)
    if not pdf_file.exists():
        raise FileNotFoundError(f"PDF文件不存在: {pdf_path}")

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

    print(f"\n{'='*60}")
    print(f"处理文件: {pdf_file.name}")
    print(f"{'='*60}")

    # 1. 提取PDF文本
    print("\n[1/3] 提取PDF文本...")
    doc = fitz.open(pdf_path)
    pages_content = []
    total_chars = 0

    for page_num in range(len(doc)):
        page = doc[page_num]
        text = page.get_text()
        total_chars += len(text)
        pages_content.append({
            "page_num": page_num + 1,
            "text": text,
            "start_pos": 0,
            "end_pos": len(text),
        })

    doc.close()
    print(f"      共 {len(pages_content)} 页, {total_chars} 字符")

    # 2. 切分章节
    print("\n[2/3] 章节切分...")
    splitter = SimplePdfTextSplitter(
        enable_validation=True,
        expected_chapters=expected_chapters 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. 获取验证报告
    print("\n[3/3] 章节规范检查...")
    validation_report = splitter.get_validation_report()

    # 4. 构建结构化数据输出
    structured_data: Dict[str, Dict[str, str]] = {}
    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

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

    result = {
        "metadata": {
            "source_file": str(pdf_path),
            "total_pages": len(pages_content),
            "total_chars": total_chars,
            "extraction_time": current_time,
            "chunk_count": len(chunks),
        },
        "validation_report": validation_report,
        "structured_data": structured_data,
        "chunks": [
            {
                "chunk_id": c["chunk_id"],
                "section_label": c["section_label"],
                "chapter_classification": c["chapter_classification"],
                "content_length": len(c["review_chunk_content"]),
                "content_preview": c["review_chunk_content"][:200] + "..." if len(c["review_chunk_content"]) > 200 else c["review_chunk_content"],
            }
            for c in chunks
        ],
    }

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

    # 6. 输出验证报告
    if verbose:
        print_validation_report(validation_report)
        print(f"\n{'='*60}")
        print(f"结果已保存: {output_file}")
        print(f"{'='*60}")

    return result


def print_validation_report(report: Dict[str, Any]) -> None:
    """打印验证报告"""
    print("\n" + "-"*60)
    print("章节规范检查报告")
    print("-"*60)

    summary = report.get("summary", {})
    total = summary.get("total", 0)
    valid = summary.get("valid", 0)
    invalid = summary.get("invalid", 0)

    print(f"\n总计: {total} 个章节 | 规范: {valid} | 异常: {invalid}")

    # 按状态分组显示
    valid_chapters = []
    invalid_chapters = []

    for r in report.get("results", []):
        if r["is_valid"]:
            valid_chapters.append(r)
        else:
            invalid_chapters.append(r)

    # 显示异常章节
    if invalid_chapters:
        print(f"\n⚠ 异常章节 ({len(invalid_chapters)}个):")
        for r in invalid_chapters:
            print(f"\n  ✗ {r['chapter']}")
            if r.get("issues"):
                for issue in r["issues"]:
                    print(f"    ! {issue}")
            if r.get("invalid_sections"):
                print(f"    - 发现 {len(r['invalid_sections'])} 个不规范节标题")
                for sec in r["invalid_sections"][:3]:
                    print(f"      · {sec[:60]}")

    # 显示规范章节
    if valid_chapters:
        print(f"\n✓ 规范章节 ({len(valid_chapters)}个):")
        for r in valid_chapters:
            if r["chapter"] != "未分类前言":  # 跳过默认章节
                section_info = f" ({r['section_count']}节)" if r.get("section_count") else ""
                print(f"  ✓ {r['chapter']}{section_info}")

    # 未分类内容
    uncategorized = report.get("uncategorized_content", [])
    if uncategorized:
        print(f"\n⚠ 未分类内容 (位于第一章之前):")
        for line in uncategorized[:5]:
            print(f"  > {line[:80]}")

    print("-"*60)


def main():
    parser = argparse.ArgumentParser(
        description="简化版PDF章节提取工具",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  python simple_extract_cli.py document.pdf
  python simple_extract_cli.py document.pdf --expected 第一章 第二章 第三章
  python simple_extract_cli.py document.pdf -o ./output
        """
    )

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

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

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

    parser.add_argument(
        "--quiet", "-q",
        action="store_true",
        help="静默模式，减少输出"
    )

    args = parser.parse_args()

    try:
        result = extract_and_validate(
            pdf_path=args.pdf_path,
            expected_chapters=args.expected,
            output_dir=args.output,
            verbose=not args.quiet
        )

        # 返回码：有异常章节则返回1
        invalid_count = result.get("validation_report", {}).get("summary", {}).get("invalid", 0)
        if invalid_count > 0:
            print(f"\n注意: 发现 {invalid_count} 个异常章节")
            sys.exit(1)
        else:
            print("\n✓ 所有章节符合规范")
            sys.exit(0)

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


if __name__ == "__main__":
    main()
