#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：element_mapping_service.py
模块描述：元素映射表服务，从前端提供的 key-value 映射表 JSON 中根据步骤描述匹配稳定选择器

作者：czj
创建日期：2026-08-11
最后修改：2026-08-11

设计说明：
- 映射表 JSON 是 Playwright 执行器的最高优先级选择器来源（selector priority: element_mapping > ...）
- 支持三种匹配策略：精确匹配（关键词包含）、模糊匹配（jieba 分词 + 相似度）、上下文辅助
- 容错：JSON 缺失/损坏时自动禁用，静默回退到原有定位策略
"""

import json
import logging
import os
import re
from difflib import SequenceMatcher
from typing import Any, Dict, List, Optional

import jieba

logger = logging.getLogger(__name__)

# 默认映射表文件路径（相对 backend/ 工作目录）
DEFAULT_MAPPING_FILE = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
    "data",
    "elements_mapping.json",
)

# 模糊匹配相似度阈值
FUZZY_MATCH_THRESHOLD = 0.7

# 精确匹配最低置信度阈值（低于此值则回退到模糊匹配）
EXACT_MATCH_MIN_SCORE = 6.0

# 同义词映射（用于精确匹配无法覆盖的语义等价关系）
SYNONYM_MAP = {
    "新建": "创建",
    "创建": "新建",
    "新增": "创建",
}

# 映射表优先级（最高）
MAPPING_PRIORITY = 1


class ElementMappingService:
    """
    元素映射表服务

    从元素映射表 JSON 文件中加载元素 -> 选择器映射，根据步骤描述匹配返回稳定选择器。

    Attributes:
        mapping_file (str): 映射表 JSON 文件路径
        _elements (dict): 已加载的元素映射 {映射键: {selector, type, tier, description}}
        _enabled (bool): 映射表是否可用（JSON 缺失/损坏时为 False）
        _index (dict): 预构建的匹配索引，加速查询
    """

    def __init__(self, mapping_file: str = DEFAULT_MAPPING_FILE):
        self.mapping_file = mapping_file
        self._elements: Dict[str, Dict[str, Any]] = {}
        self._enabled = False
        self._index: Dict[str, List[str]] = {}  # 中文关键词 -> 映射键列表
        self._action_map: Dict[str, str] = {}   # 动作类型 -> 映射键
        self._load()

    # ==================== 加载 ====================

    def _load(self) -> None:
        """加载映射表 JSON 文件，失败时自动禁用"""
        self._elements = {}
        self._index = {}
        self._action_map = {}
        self._enabled = False

        if not os.path.exists(self.mapping_file):
            logger.warning(f"[元素映射表] 文件不存在，映射表已禁用: {self.mapping_file}")
            return

        try:
            with open(self.mapping_file, "r", encoding="utf-8") as f:
                data = json.load(f)

            elements = data.get("elements", {})
            if not isinstance(elements, dict) or not elements:
                logger.warning("[元素映射表] JSON 中 elements 为空，映射表已禁用")
                return

            self._elements = elements

            # 构建中文关键词 -> 映射键索引
            for key in elements:
                for kw in self._split_keywords(key):
                    self._index.setdefault(kw, []).append(key)

            self._enabled = True
            logger.info(f"[元素映射表] 加载成功: {len(elements)} 个元素, 来源: {data.get('source', '未知')}")
        except json.JSONDecodeError as e:
            logger.error(f"[元素映射表] JSON 解析失败，映射表已禁用: {e}")
        except Exception as e:
            logger.error(f"[元素映射表] 加载异常，映射表已禁用: {e}")

    def reload(self) -> bool:
        """热重载映射表文件

        Returns:
            bool: 重载后映射表是否可用
        """
        self._load()
        return self._enabled

    # ==================== 查询 ====================

    def get_selector(
        self,
        step_name: str,
        action: str = "click",
        context: Optional[Dict] = None,
    ) -> Optional[Dict[str, Any]]:
        """
        根据步骤描述和上下文，从映射表获取选择器

        Args:
            step_name: 步骤描述（如"点击创建会议按钮"）
            action: 动作类型（click / fill 等）
            context: 上下文信息（当前页面、前序步骤等）

        Returns:
            {"selector": "...", "type": "css", "confidence": 1.0, "key": "..."} 或 None
        """
        if not self._enabled or not step_name:
            return None

        # 1. 精确匹配（关键词包含）
        exact = self._exact_match(step_name)
        if exact:
            return self._build_result(exact, confidence=1.0)

        # 2. 模糊匹配（jieba 分词 + 相似度）
        fuzzy = self._fuzzy_match(step_name)
        if fuzzy:
            return self._build_result(fuzzy[0], confidence=fuzzy[1])

        # 3. 上下文辅助匹配（结合前序步骤判断所在功能分类）
        if context:
            ctx_match = self._context_match(step_name, context)
            if ctx_match:
                return self._build_result(ctx_match, confidence=0.9)

        return None

    def get_all_keys(self) -> List[str]:
        """返回所有映射键列表（用于调试）"""
        return list(self._elements.keys())

    def is_enabled(self) -> bool:
        """映射表是否可用"""
        return self._enabled

    # ==================== 匹配策略 ====================

    @staticmethod
    def _split_keywords(key: str) -> List[str]:
        """
        从映射键中拆分中文关键词

        例如："全部功能-会议预约-创建会议" -> ["会议预约", "创建会议"]
        去除前缀层级词（导航栏/首页/功能中心/全部功能/置顶功能/常用功能/筛选器）
        """
        # 去除层级前缀
        cleaned = key
        for prefix in ["导航栏-", "首页-", "功能中心-置顶功能-", "功能中心-常用功能-",
                       "功能中心-搜索", "全部功能-筛选器-", "全部功能-", "功能中心-"]:
            if cleaned.startswith(prefix):
                cleaned = cleaned[len(prefix):]
                break

        # 按 - 拆分得到各段
        parts = [p for p in cleaned.split("-") if p]
        result = []

        # 每段作为一个关键词（如"会议预约"、"创建会议"）
        result.extend(parts)

        # 整个 cleaned 也作为一个关键词（如"会议预约-创建会议"）
        if len(parts) > 1:
            result.append(cleaned)

        return result

    def _expand_synonyms(self, keyword: str) -> List[str]:
        """
        将步骤关键词中的常见同义词替换为映射表用词，返回所有变体

        例如："新建会议" -> ["新建会议", "创建会议"]（新建↔创建）
        "创建会议按钮" -> ["创建会议按钮", "新建会议按钮"]
        """
        variants = {keyword}
        for src, tgt in SYNONYM_MAP.items():
            if src in keyword:
                variants.add(keyword.replace(src, tgt))
            if tgt in keyword:
                variants.add(keyword.replace(tgt, src))
        return list(variants)

    def _exact_match(self, step_name: str) -> Optional[str]:
        """
        精确匹配：步骤描述包含映射键中的完整关键词

        采用"强匹配/弱匹配"评分模型：
        - 强匹配：步骤关键词完整包含映射键关键词（sk==kk 或 kk in sk），权重高
        - 弱匹配：步骤关键词是映射键关键词的子串（sk in kk），如"会议" in "会议服务统计"，权重低

        要求至少 1 个强匹配，或 2 个以上弱匹配，才判定为精确命中。
        这解决了"创建会议"误配"会议服务统计"（仅弱匹配"会议"）的问题。
        """
        step_clean = self._clean_step_name(step_name)
        step_keywords = self._tokenize(self._clean_step_name_without_elem(step_name))

        best_key = None
        best_score = 0.0

        for key in self._elements:
            key_kws = self._split_keywords(key)
            score = 0.0
            strong_count = 0
            weak_count = 0

            for sk in step_keywords:
                if len(sk) < 2:
                    continue

                # 展开同义词变体
                variants = self._expand_synonyms(sk)

                # 强匹配：映射键关键词完整包含在步骤关键词（或其同义词变体）中
                strong_hit = False
                for var in variants:
                    for kk in key_kws:
                        if var == kk or kk in var:
                            score += len(kk) * 2.0
                            strong_count += 1
                            strong_hit = True
                            break
                    if strong_hit:
                        break

                if strong_hit:
                    continue

                # 弱匹配：步骤关键词是映射键关键词的子串
                for kk in key_kws:
                    if sk in kk:
                        score += 1.0
                        weak_count += 1
                        break

            # 置信度要求：至少 1 个强匹配，或至少 2 个弱匹配
            if strong_count == 0 and weak_count < 2:
                continue

            # 动作适配：步骤含"分类/筛选"时优先筛选器，含"抽屉"时优先导航栏开关
            if ("分类" in step_clean or "筛选" in step_clean) and "筛选器" in key:
                score += 3.0
            if "搜索" in step_clean and "搜索" in key:
                score += 3.0
            if "抽屉" in step_clean and "抽屉" in key:
                score += 3.0

            # 完整映射键段出现在步骤中，额外加分（更精确的命中）
            for kk in key_kws:
                if len(kk) >= 3 and kk in step_clean:
                    score += 2.0
                    break

            if score > best_score:
                best_score = score
                best_key = key

        return best_key if best_key else None

    def _fuzzy_match(self, step_name: str) -> Optional[tuple]:
        """
        模糊匹配：jieba 分词后计算相似度，取最高分（阈值 >= 0.7）

        Returns:
            (映射键, 相似度) 或 None
        """
        step_clean = self._clean_step_name(step_name)
        step_keywords = self._tokenize(step_clean)
        if not step_keywords:
            return None

        best_key = None
        best_score = FUZZY_MATCH_THRESHOLD

        for key, info in self._elements.items():
            key_kws = self._split_keywords(key)
            # 计算步骤关键词与映射键关键词的最大匹配度
            score = 0.0
            for sk in step_keywords:
                if len(sk) < 2:
                    continue
                for kk in key_kws:
                    sim = SequenceMatcher(None, sk, kk).ratio()
                    # 包含关系也算高分
                    if sk in kk or kk in sk:
                        sim = max(sim, 0.85)
                    score = max(score, sim)

            # 结合 description 匹配
            desc = info.get("description", "")
            for sk in step_keywords:
                if len(sk) >= 2 and sk in desc:
                    score = max(score, 0.9)

            if score >= best_score:
                best_score = score
                best_key = key

        if best_key:
            return best_key, best_score
        return None

    def _context_match(self, step_name: str, context: Dict) -> Optional[str]:
        """
        上下文辅助匹配：结合当前页面 URL、前序步骤判断所在功能分类

        通过在映射键中加入当前上下文分类过滤，缩小匹配范围。
        """
        category = context.get("category") or context.get("current_module")
        if not category:
            return None

        step_clean = self._clean_step_name(step_name)
        step_keywords = self._tokenize(step_clean)

        # 在指定分类下匹配
        prefix = f"全部功能-{category}-"
        for kk in self._elements:
            if not kk.startswith(prefix):
                continue
            key_kws = self._split_keywords(kk)
            for sk in step_keywords:
                if len(sk) < 2:
                    continue
                for kkw in key_kws:
                    if sk in kkw or kkw in sk:
                        return kk
        return None

    # ==================== 辅助方法 ====================

    def _build_result(self, key: str, confidence: float) -> Dict[str, Any]:
        """构建匹配结果"""
        info = self._elements.get(key, {})
        return {
            "selector": info.get("selector", key),
            "type": info.get("type", "css"),
            "confidence": confidence,
            "key": key,
            "description": info.get("description", ""),
            "tier": info.get("tier", ""),
            "priority": MAPPING_PRIORITY,
        }

    @staticmethod
    def _clean_step_name(step_name: str) -> str:
        """清理步骤描述：去除动作词、标点、元素类型词"""
        # 去除【】内容保留（如"点击【新建会议】" -> "新建会议"）
        cleaned = step_name
        # 去除常见动作前缀
        for action_word in ["点击", "单击", "双击", "输入", "填写", "填入", "选择",
                            "打开", "展开", "收起", "导航到", "进入", "按下", "勾选",
                            "取消", "悬停", "滚动", "等待", "检查", "验证", "查看"]:
            cleaned = re.sub(rf"^{action_word}", "", cleaned)
        # 去除元素类型词
        for elem_word in ["按钮", "输入框", "链接", "图标", "菜单", "标签", "选项卡",
                          "下拉框", "复选框", "单选框", "抽屉", "导航", "选项"]:
            cleaned = cleaned.replace(elem_word, "")
        # 去除括号和引号
        cleaned = re.sub(r"[【】\[\]（）()\"']", "", cleaned)
        return cleaned.strip()

    @staticmethod
    def _clean_step_name_without_elem(step_name: str) -> str:
        """清理步骤描述：仅去除动作词和标点，保留元素类型词用于匹配"""
        cleaned = step_name
        for action_word in ["点击", "单击", "双击", "输入", "填写", "填入", "选择",
                            "打开", "展开", "收起", "导航到", "进入", "按下", "勾选",
                            "取消", "悬停", "滚动", "等待", "检查", "验证", "查看"]:
            cleaned = re.sub(rf"^{action_word}", "", cleaned)
        cleaned = re.sub(r"[【】\[\]（）()\"']", "", cleaned)
        return cleaned.strip()

    @staticmethod
    def _tokenize(text: str) -> List[str]:
        """jieba 分词 + 提取关键段"""
        if not text:
            return []
        # 优先按 - 拆分（映射键风格）
        parts = [p for p in re.split(r"[-—\s]", text) if p]
        tokens = []
        for p in parts:
            tokens.append(p)
            # 对中文段做 jieba 分词
            for seg in jieba.lcut(p):
                seg = seg.strip()
                if len(seg) >= 2 and seg not in tokens:
                    tokens.append(seg)
        # 去重
        seen = set()
        result = []
        for t in tokens:
            if t not in seen:
                seen.add(t)
                result.append(t)
        return result


# 全局单例（懒加载）
_global_service: Optional[ElementMappingService] = None


def get_element_mapping_service() -> ElementMappingService:
    """获取全局 ElementMappingService 单例"""
    global _global_service
    if _global_service is None:
        _global_service = ElementMappingService()
    return _global_service