from __future__ import annotations

from typing import List, Dict
from dataclasses import asdict

# 框架依赖
from ..framework.command import Command
from ..framework.context import Context
from ..framework.command_registry import CommandRegistry

# 解析工具方法（仅保留元数据解析）
from ..common.word.docx_file_parse_util import (
    extract_docx_content_with_metadata,
)


class DocxFileParseCommand(Command):
    """
    框架命令子类：按“标题-表格-脚注/段落”分块（仅元数据）。
    仅使用 `extract_docx_content_with_metadata` 进行解析。
    """

    def is_satisfied(self, context: Context) -> bool:
        return context.has_document()

    def execute(self, context: Context) -> Context:
        # 解析输入路径（支持文件或文件夹），仅处理 .docx
        paths = context.resolve_document_paths(patterns=["*.docx"])
        if not paths:
            context.add_error("No DOCX files resolved from context")
            return context

        # 将解析得到的 TableItem 列表转为结构化字典，并写入 Context.sections
        parsed_sections: List[Dict] = []
        for p in paths:
            sections = extract_docx_content_with_metadata(str(p))
            for sec in sections:
                d = asdict(sec)
                d["source_file"] = str(p)
                parsed_sections.append(d)

        # 更新上下文
        context.doc_type = "docx"
        context.sections = parsed_sections
        context.processing_summary["title_table_footnote_partition"] = {
            "files_processed": len(paths),
            "sections_extracted": len(parsed_sections),
            "mode": "metadata_only",
        }
        return context


# 注册到命令注册表，便于 Pipeline 通过 YAML 创建
CommandRegistry.register("DocxFileParseCommand", DocxFileParseCommand)