# -*- coding: utf-8 -*-
"""
문서 템플릿 분석기 v5.1 (자동 추출 방식)
"""
import json
from pathlib import Path
from .tools import (
    page_setup, font, char_style, para_style, border_fill,
    table, header_footer, section, style_def, numbering,
    image, content_order
)

class DocTemplateAnalyzer:
    def analyze(self, parsed: dict) -> dict:
        raw_xml = parsed.get("raw_xml", {})
        extractors = {
            "page":         lambda: page_setup.extract(raw_xml, parsed),
            "fonts":        lambda: font.extract(raw_xml, parsed),
            "char_styles":  lambda: char_style.extract(raw_xml, parsed),
            "para_styles":  lambda: para_style.extract(raw_xml, parsed),
            "border_fills": lambda: border_fill.extract(raw_xml, parsed),
            "tables":       lambda: table.extract(raw_xml, parsed),
            "header":       lambda: header_footer.extract_header(raw_xml, parsed),
            "footer":       lambda: header_footer.extract_footer(raw_xml, parsed),
            "section":      lambda: section.extract(raw_xml, parsed),
            "styles":       lambda: style_def.extract(raw_xml, parsed),
            "numbering":    lambda: numbering.extract(raw_xml, parsed),
            "images":       lambda: image.extract(raw_xml, parsed),
            "content_order":lambda: content_order.extract(raw_xml, parsed),
        }
        result = {}
        for key, extractor in extractors.items():
            try:
                value = extractor()
                if value is not None:
                    result[key] = value
            except Exception as e:
                result.setdefault("_errors", []).append(f"{key}: {type(e).__name__}: {e}")
        return result

    def merge_user_config(self, template_info: dict, config: dict) -> dict:
        user_overrides = config.get("user_overrides", {})
        if not user_overrides:
            return template_info
        template_info["user_overrides"] = user_overrides
        return template_info

    def save_style(self, template_info: dict, save_path: Path) -> Path:
        save_path = Path(save_path)
        save_path.parent.mkdir(parents=True, exist_ok=True)
        with open(save_path, 'w', encoding='utf-8') as f:
            json.dump(template_info, f, ensure_ascii=False, indent=2)
        return save_path
