#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
模块名称：migrate_mapping_v2.py
模块描述：元素映射表 v1 扁平结构 → v2 显式字典结构迁移脚本（离线）

v2 格式（前端开发可维护，见 PRD 第五章）：
{
  "version": "2.0", "source": "迁移自 v1 231 条",
  "pages": [
    { "id": "创建会议", "name": "新建会议",
      "elements": { "预定会议": {"selectors": [".time_btn .btns:has-text(\"预定会议\")"], "type": "tab"} } }
  ],
  "shared_elements": { "登录按钮": {"selectors": ["button:has-text(\"登录\")"], "type": "button"} }
}

说明：
- 按页面 token 归组（与 element_mapping_service._page_id_for 同规则）
- 键保留原语义名（形如"创建会议-预定会议"），值为 {selectors:[原selector], type, description}
- 纯显式字典，无任何评分规则

用法：
    cd backend && python scripts/migrate_mapping_v2.py [输出路径]
    默认输出 backend/data/elements_mapping_v2.json

作者：czj
创建日期：2026-08-18
"""

import json
import os
import sys

# 允许从任意工作目录运行
# 脚本位于 backend/scripts/，上两级 = backend；映射表在 backend/app/data/
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC_FILE = os.path.join(BASE_DIR, "app", "data", "elements_mapping.json")
OUT_DIR = os.path.join(BASE_DIR, "app", "data")

# 页面 token（与 element_mapping_service._page_id_for 保持一致）
_PAGE_TOKENS = ("创建会议", "会议详情", "会议列表", "会议预约", "登录页", "首页",
                "会议室", "会议模板", "个人日程", "管理看板", "信息发布", "预订2.0")


def page_id_for(key: str, info: dict) -> str:
    tier = info.get("tier") or ""
    for tok in _PAGE_TOKENS:
        if tok in tier:
            return tok
    for tok in _PAGE_TOKENS:
        if key.startswith(f"{tok}-"):
            return tok
    return tier or "默认"


def migrate() -> dict:
    with open(SRC_FILE, "r", encoding="utf-8") as f:
        data = json.load(f)
    elements = data.get("elements", {})

    pages: dict = {}
    for key, info in elements.items():
        pid = page_id_for(key, info)
        page = pages.setdefault(pid, {
            "id": pid,
            "name": pid,
            "elements": {},
        })
        # 保留原 selector（v1 每个条目一个 selector）
        page["elements"][key] = {
            "selectors": [info["selector"]] if isinstance(info.get("selector"), str) else (info.get("selectors") or []),
            "type": info.get("type", "css"),
            "description": info.get("description", ""),
        }

    return {
        "version": "2.0",
        "source": f"迁移自 v1 {len(elements)} 条",
        "pages": [pages[pid] for pid in sorted(pages)],
        "shared_elements": {},
    }


def main() -> None:
    out = sys.argv[1] if len(sys.argv) > 1 else os.path.join(OUT_DIR, "elements_mapping_v2.json")
    result = migrate()
    with open(out, "w", encoding="utf-8") as f:
        json.dump(result, f, ensure_ascii=False, indent=2)
    n_pages = len(result["pages"])
    n_elements = sum(len(p["elements"]) for p in result["pages"])
    print(f"迁移完成: {n_pages} 页, {n_elements} 元素 → {out}")


if __name__ == "__main__":
    main()
