"""解析和应用标准词映射的辅助工具。"""

import json
import re


def _split_standard_word_variants(variants_value):
    """使用支持的分隔符拆分变体词。"""
    if isinstance(variants_value, list):
        raw_variants = variants_value
    else:
        raw_variants = re.split(r"[、，,\s]+", str(variants_value or ""))

    return [
        variant.strip()
        for variant in raw_variants
        if isinstance(variant, str) and variant.strip()
    ]


def parse_standard_word_mappings(config_value):
    """
    从 JSON 或旧版文本行解析标准词映射配置。

    支持的格式:
    1. JSON 字符串 / Python 列表:
       [{"standard": "标准词", "variants": ["常用词1", "常用词2"]}]
    2. 旧版文本行:
       标准词：常用词1、常用词2
    """
    if not config_value:
        return []

    raw_entries = []

    if isinstance(config_value, list):
        raw_entries = config_value
    elif isinstance(config_value, dict):
        raw_entries = [config_value]
    elif isinstance(config_value, str):
        normalized_value = config_value.strip()
        if not normalized_value:
            return []

        if normalized_value[0] in ["[", "{"]:
            try:
                parsed_value = json.loads(normalized_value)
            except (TypeError, ValueError, json.JSONDecodeError):
                parsed_value = None

            if isinstance(parsed_value, list):
                raw_entries = parsed_value
            elif isinstance(parsed_value, dict):
                raw_entries = [parsed_value]

        if not raw_entries:
            for raw_line in normalized_value.splitlines():
                line = raw_line.strip()
                if not line:
                    continue

                if "：" in line:
                    standard_word, variants_value = line.split("：", 1)
                elif ":" in line:
                    standard_word, variants_value = line.split(":", 1)
                else:
                    continue

                raw_entries.append(
                    {
                        "standard": standard_word.strip(),
                        "variants": _split_standard_word_variants(variants_value),
                    }
                )
    else:
        return []

    normalized_entries = []
    for entry in raw_entries:
        if not isinstance(entry, dict):
            continue

        standard_word = (
            entry.get("standard")
            or entry.get("standard_word")
            or entry.get("target")
            or ""
        )
        standard_word = str(standard_word).strip()
        if not standard_word:
            continue

        variants = _split_standard_word_variants(
            entry.get("variants")
            or entry.get("common_words")
            or entry.get("sources")
            or ""
        )

        deduplicated_variants = []
        seen_variants = set()
        for variant in variants:
            if variant == standard_word or variant in seen_variants:
                continue
            deduplicated_variants.append(variant)
            seen_variants.add(variant)

        if deduplicated_variants:
            normalized_entries.append(
                {"standard": standard_word, "variants": deduplicated_variants}
            )

    return normalized_entries


def apply_standard_word_mappings_with_details(text, config_value):
    """应用映射并返回映射后的文本以及已应用的映射详情。"""
    if not text or not isinstance(text, str):
        return text, []

    mapping_entries = parse_standard_word_mappings(config_value)
    if not mapping_entries:
        return text, []

    variant_to_standard = {}
    ordered_variants = []

    for mapping_entry in mapping_entries:
        standard_word = mapping_entry["standard"]
        for variant in mapping_entry["variants"]:
            if variant in variant_to_standard:
                continue
            variant_to_standard[variant] = standard_word
            ordered_variants.append(variant)

    if not ordered_variants:
        return text, []

    replacement_pattern = re.compile(
        "|".join(
            re.escape(variant)
            for variant in sorted(ordered_variants, key=len, reverse=True)
        )
    )

    applied_mappings = []

    def replace_match(match):
        variant = match.group(0)
        standard_word = variant_to_standard.get(variant, variant)
        if standard_word != variant:
            applied_mappings.append({"from": variant, "to": standard_word})
        return standard_word

    mapped_text = replacement_pattern.sub(replace_match, text)
    return mapped_text, applied_mappings


def apply_standard_word_mappings(text, config_value):
    """将配置的标准词映射应用到校正后的 ASR 文本。"""
    mapped_text, _ = apply_standard_word_mappings_with_details(text, config_value)
    return mapped_text
