"""
通用 JSON 结果写出器

基于 file_parse 接口的 ResultWriter，实现将处理结果写为
“完整结果”风格的 JSON，便于 PDF / DOCX 等不同 worker 复用。
"""

from __future__ import annotations

import json
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Optional

from ..config.provider import default_config_provider
from ..interfaces import DocumentSource, ResultWriter


class DefaultJsonResultWriter(ResultWriter):
    """通用的 JSON Writer，可被各 worker 直接复用。"""

    def __init__(self) -> None:
        self._cfg = default_config_provider
        self.last_json_path: Path | None = None

    def write(self, result: Dict[str, Any]) -> None:
        source = result.get("source")
        if isinstance(source, DocumentSource) and source.path is not None:
            file_path = Path(source.path)
        else:
            file_path = Path("unknown_source")

        # 允许外部通过 meta.output_dir 指定输出目录，否则使用默认
        meta: Dict[str, Any] = result.get("meta", {}) or {}
        output_dir_override: Optional[str | Path] = meta.get("output_dir")

        if output_dir_override:
            output_dir = Path(output_dir_override)
        else:
            output_dir_name = self._cfg.get("output.default_dir_name", "分类切分结果")
            output_dir = file_path.parent / output_dir_name
        output_dir.mkdir(parents=True, exist_ok=True)

        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        json_file = output_dir / f"{file_path.stem}_完整结果_{timestamp}.json"

        toc_info: Dict[str, Any] = result.get("toc_info", {}) or {}
        classification: Dict[str, Any] = result.get("classification", {}) or {}
        chunks = result.get("chunks", []) or []

        complete_toc_list = []
        for idx, item in enumerate(toc_info.get("toc_items", []), 1):
            complete_toc_list.append(
                {
                    "index": idx,
                    "title": item.get("title", ""),
                    "page": item.get("page", ""),
                    "level": item.get("level", 1),
                    "original": item.get("original", ""),
                }
            )

        output_data: Dict[str, Any] = {
            "source_file": str(file_path),
            "process_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "toc_summary": {
                "total_items": toc_info.get("toc_count", len(complete_toc_list)),
                "toc_pages": toc_info.get("toc_pages", []),
            },
            "complete_toc_list": complete_toc_list,
            "classification": classification,
            "chunks": chunks,
        }

        with json_file.open("w", encoding="utf-8") as f:
            json.dump(output_data, f, ensure_ascii=False, indent=2)

        self.last_json_path = json_file


