# -*- coding: utf-8 -*-
# 从佳尔灵英文目录 PDF 生成平替对照表 (JELPC → 我方型号)
# 原理: 系列对照 (SQ↔KCS, SI↔KC, SIB↔KCB, SC/SU↔KS/KSU, SCT↔KSB, MAL/MALC 同名)
#       + 抽取 PDF 中的 系列+缸径x行程 组合 → 构造我方基础型型号 → 必须存在于我方 CSV 才写入
# 输出: OnebotCatalog\onebot-data\catalog\crossref.csv
# 用法: python tools\jelpc-crossref.py
import fitz, re, os, sys

# 路径基于脚本自身位置 (OnebotCatalog\onebot-data\tools\ → 上溯两级到 OnebotCatalog)
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
PDF = os.path.join(ROOT, '4_JELPC_E-Catalog_EN.pdf')
CSV_DIR = os.path.join(ROOT, 'onebot-data', 'catalog', 'csv')
OUT = os.path.join(ROOT, 'onebot-data', 'catalog', 'crossref.csv')

# 佳尔灵系列 → (我方系列, 我方基础型号段, 是否双轴字母映射)
# 我方型号构造规则 (与 build-onebot 一致):
#   KC类:  <我方系列><type><缸径>-<行程>          type: 00 标准 / 02 双轴 / 03 双轴可调
#   MAL类: <type段><缸径>-<行程>                  type段: MAL / MALC
SERIES_MAP = {
    "SI":   ("KC",   "00"),
    "SIB":  ("KCB",  ""),
    "SQ":   ("KCS",  "00"),
    "SC":   ("KS",   "00"),
    "SU":   ("KSU",  "00"),
    "SCT":  ("KSB",  ""),
    "MAL":  ("MAL",  "MAL"),
    "MALC": ("MALC", "MALC"),
}

def main():
    # 1) 我方型号集合 (CSV 第 1 列)
    ours = set()
    for fn in os.listdir(CSV_DIR):
        if not fn.endswith('.csv'):
            continue
        with open(os.path.join(CSV_DIR, fn), encoding='utf-8-sig') as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith('model_code'):
                    continue
                code = line.split(',')[0].strip()
                if code:
                    ours.add(code)

    # 2) 佳尔灵 PDF 全文本
    doc = fitz.open(PDF)
    full = '\n'.join(doc[i].get_text() for i in range(doc.page_count))
    doc.close()

    # 3) 抽取 系列+型号段+缸径-行程 组合
    rows = []   # (jpc_code, our_code)
    seen = set()
    for jseries, (oseries, otype) in SERIES_MAP.items():
        # 型号段字母: 标准(无)/D(双轴)/J(双轴可调) 等
        pat = re.compile(r'\b' + jseries + r'([A-Z]?)(\d{1,3})-(\d{1,4})\b')
        for m in pat.finditer(full):
            seg = m.group(1)
            bore = m.group(2)
            stroke = m.group(3)
            if len(stroke) > 3:   # 过滤表格数字误匹配 (行程一般 1~3 位)
                continue
            jpc_code = m.group(0)
            # 构造我方型号
            if oseries in ("MAL", "MALC"):
                our = otype + bore + '-' + stroke
            elif oseries == "KSB":
                our = oseries + bore + '-0x' + stroke   # 双行程: 行程1=0 行程2=stroke (占位)
            else:
                t = {"": "00", "D": "02", "J": "03"}.get(seg, "00")
                our = oseries + t + bore + '-' + stroke
            if our not in ours:
                continue
            key = (jpc_code, our)
            if key in seen:
                continue
            seen.add(key)
            rows.append((jpc_code, our))

    rows.sort(key=lambda x: (x[1], x[0]))
    print(f'生成对照 {len(rows)} 行 (我方型号已校验存在)')

    # 4) 写 crossref.csv (覆盖; 其余品牌行请自行追加)
    with open(OUT, 'w', encoding='utf-8-sig', newline='') as f:
        f.write('brand,foreign_model,our_model,note\n')
        for jpc, our in rows:
            f.write(f'JELPC,{jpc},{our},基础型平替(待核对)\n')
    print('已写:', OUT)

if __name__ == '__main__':
    main()
