#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""在 index/app 的「客户管理」下加入客户拉通大表 v11 正式入口。"""
import pathlib, shutil

ROOT = pathlib.Path('/Users/liuxinyuan/Desktop/Hermes输出-工作类')
FILES = [ROOT / '工具/index.html', ROOT / '工具/app.html']

TAB_LINE = "  { id: 'customers', group: 'cust', label: '客户', icon: '📋', lines: ['da'] },\n"
TAB_ADD = "  { id: 'customerRollup', group: 'cust', label: '客户拉通大表', icon: '🧩', lines: ['da','ls'] },\n"

CASE_NEEDLE = "    case 'customers': renderCustomers(main); break;\n"
CASE_ADD = "    case 'customers': renderCustomers(main); break;\n    case 'customerRollup': renderCustomerRollup(main); break;\n"

FUNC = r'''
/* ===== 客户拉通大表 V2 ===== */
function renderCustomerRollup(main){
  main.innerHTML =
    '<div style="display:flex;align-items:center;gap:12px;margin-bottom:12px;flex-wrap:wrap">' +
      '<h2 style="font-size:19px;font-weight:900;margin:0">🧩 客户拉通大表 · V2</h2>' +
      '<span style="color:var(--sub);font-size:12.5px">项目推移 / 活动录入 V2 / 商机审批 / 任务闭环 / 活动质量</span>' +
      '<span style="flex:1"></span>' +
      '<a href="/工具/客户拉通大表_demo_v11_活动录入V2同步_20261101_V01.html" target="_blank" ' +
        'style="border:1px solid var(--border);background:#fff;border-radius:8px;padding:6px 12px;font-size:12px;color:var(--pri);text-decoration:none;font-weight:700">新窗口打开</a>' +
    '</div>' +
    '<div style="height:calc(100vh - 180px);min-height:680px;background:#fff;border-radius:10px;overflow:hidden;border:1px solid var(--border)">' +
      '<iframe src="/工具/客户拉通大表_demo_v11_活动录入V2同步_20261101_V01.html?embed=1&v=20261101" ' +
        'style="width:100%;height:100%;border:none" title="客户拉通大表 V2"></iframe>' +
    '</div>';
}
'''

for p in FILES:
    s = p.read_text(encoding='utf-8')
    if "customerRollup" in s:
        print('already patched', p)
        continue
    bak = p.with_name(p.stem + '_backup_customerrollup_20261101' + p.suffix)
    if not bak.exists():
        shutil.copy2(p, bak)
    assert TAB_LINE in s, p
    s = s.replace(TAB_LINE, TAB_LINE + TAB_ADD, 1)
    assert CASE_NEEDLE in s, p
    s = s.replace(CASE_NEEDLE, CASE_ADD, 1)
    # 插在 renderCustToolbar 前
    needle = 'function renderCustToolbar()'
    assert needle in s, p
    s = s.replace(needle, FUNC + '\n' + needle, 1)
    p.write_text(s, encoding='utf-8')
    print('patched', p, len(s))
