from __future__ import annotations

import re
from pathlib import Path
from typing import List, Optional
import yaml

# 引用共享 pipelines 解析工具
from .pipelines_resource import resolve_pipelines_yaml


def _resolve_config_path(config_path: Optional[str] = None) -> Path:
    """返回配置文件路径；若未提供，则指向包内 pipelines/title_table_footnote_patterns.yaml"""
    if config_path:
        return Path(config_path)
    return Path(resolve_pipelines_yaml("title_table_footnote_patterns.yaml"))


def load_title_patterns(config_path: Optional[str] = None) -> List[re.Pattern]:
    """从 YAML 加载标题匹配正则列表（`title_patterns`），忽略大小写。缺失时返回空列表。"""
    cfg_path = _resolve_config_path(config_path)
    patterns: List[str] = []
    try:
        if cfg_path.exists():
            with open(cfg_path, "r", encoding="utf-8") as f:
                data = yaml.safe_load(f) or {}
            patterns = [p for p in (data.get("title_patterns") or []) if isinstance(p, str)]
    except Exception:
        patterns = []
    return [re.compile(p, re.IGNORECASE) for p in patterns]


def load_label_patterns(config_path: Optional[str] = None) -> List[re.Pattern]:
    """从 YAML 加载用于提取最小标题标签的正则列表（`label_patterns` 或兼容 `title_label_pattern`）。"""
    cfg_path = _resolve_config_path(config_path)
    patterns: List[str] = []
    try:
        if cfg_path.exists():
            with open(cfg_path, "r", encoding="utf-8") as f:
                data = yaml.safe_load(f) or {}
            vals = data.get("label_patterns")
            if isinstance(vals, list):
                patterns = [p.strip() for p in vals if isinstance(p, str) and p.strip()]
            else:
                one = data.get("title_label_pattern")
                if isinstance(one, str) and one.strip():
                    patterns = [one.strip()]
    except Exception:
        patterns = []
    return [re.compile(p, re.IGNORECASE) for p in patterns]


def load_footnote_patterns(config_path: Optional[str] = None) -> List[re.Pattern]:
    """从 YAML 加载脚注匹配正则列表（`footnote_patterns`），忽略大小写。缺失时返回空列表。"""
    cfg_path = _resolve_config_path(config_path)
    patterns: List[str] = []
    try:
        if cfg_path.exists():
            with open(cfg_path, "r", encoding="utf-8") as f:
                data = yaml.safe_load(f) or {}
            patterns = [p for p in (data.get("footnote_patterns") or []) if isinstance(p, str)]
    except Exception:
        patterns = []
    return [re.compile(p, re.IGNORECASE) for p in patterns]