# -*- coding: utf-8 -*-
"""把 demo 前端搬进 wwwroot，并把硬编码数据源改为 fetch 真接口
 · 界面渲染代码一行不改（1:1）
 · 只替换 12 个全局数据数组 + 初始化入口 + 切换会议时重新拉取
"""
import os
import re
import shutil

SRC = '/data/www/files/rmsys'
DST = '/data/www/files/rmsys-app/backend/src/Rmsys.Api/wwwroot'

os.makedirs(os.path.join(DST, 'assets'), exist_ok=True)
for f in ['admin.html', 'pad.html', 'index.html']:
    shutil.copy2(os.path.join(SRC, f), os.path.join(DST, f))
for f in os.listdir(os.path.join(SRC, 'assets')):
    p = os.path.join(SRC, 'assets', f)
    if os.path.isfile(p):
        shutil.copy2(p, os.path.join(DST, 'assets', f))
print('[1] 已复制:', ', '.join(sorted(os.listdir(DST))))

P = os.path.join(DST, 'admin.html')
s = open(P, encoding='utf-8').read()
before = len(s.encode())

VARS = ['DEPTS', 'TYPES', 'MEETINGS', 'CADRES', 'PKGS', 'PADS', 'LOGS',
        'DOCS', 'ISSUES', 'ROLES', 'USERS', 'LOGINS']


def find_array_end(text, start):
    """从 start（指向 '['）做括号配对，忽略字符串内容"""
    depth = 0
    q = None
    esc = False
    for k in range(start, len(text)):
        ch = text[k]
        if q:
            if esc:
                esc = False
                continue
            if ch == '\\':
                esc = True
                continue
            if ch == q:
                q = None
            continue
        if ch in "'\"`":
            q = ch
            continue
        if ch in '[{':
            depth += 1
        elif ch in ']}':
            depth -= 1
            if depth == 0:
                return k
    raise ValueError('括号未闭合')


emptied = []
for v in VARS:
    m = re.search(r'var\s+' + v + r'\s*=\s*\[', s)
    if not m:
        print('   ! 未找到 var %s' % v)
        continue
    start = m.end() - 1
    end = find_array_end(s, start)
    s = s[:start] + '[]' + s[end + 1:]
    emptied.append(v)
print('[2] 已清空硬编码数组 %d 个: %s' % (len(emptied), ', '.join(emptied)))

# ---------- 注入 bootstrap ----------
BOOT = r'''
/* ==========================================================================
   数据接入：从后端 API 拉取（/api/admin/bootstrap）
   字段名与形状与原 demo 的全局数组完全一致 → 所有 render* 函数无需改动
   ========================================================================== */
var API_BASE = '';           /* 与前端同源部署时留空；跨域调试可填 http://192.168.99.133:5099 */
var BOOT_LOADED = false;

function bootstrap(keepView){
  var url = API_BASE + '/api/admin/bootstrap?meetingId=' + (ROLE.meeting || 1);
  return fetch(url, { headers: { 'Accept': 'application/json' } })
    .then(function(r){
      if(!r.ok) throw new Error('HTTP ' + r.status);
      return r.json();
    })
    .then(function(d){
      if(d.error) throw new Error(d.error);
      DEPTS   = d.depts   || [];
      TYPES   = d.types   || [];
      MEETINGS= d.meetings|| [];
      CADRES  = d.cadres  || [];
      DOCS    = d.docs    || [];
      PKGS    = d.pkgs    || [];
      PADS    = d.pads    || [];
      USERS   = d.users   || [];
      LOGINS  = d.logins  || [];
      LOGS    = d.logs    || [];
      ISSUES  = d.issues  || ISSUES;
      ROLES   = d.roles   || ROLES;
      if(d.currentMeetingId) ROLE.meeting = d.currentMeetingId;
      BOOT_LOADED = true;
      if(!keepView) ROLE.view = 'meetings';
      setView(ROLE.view);
      toast('已连接数据库 · 上会 ' + CADRES.length + ' 人 / 会议 ' + MEETINGS.length + ' 场', 'ok');
    })
    .catch(function(e){
      BOOT_LOADED = false;
      document.getElementById('content').innerHTML =
        '<div class="panel"><div class="panel-b">'
        + '<div class="sec-note warn"><b>无法连接后端接口</b><br>' + esc(e.message)
        + '<br><br>请确认 API 已启动：<code>dotnet run --project src/Rmsys.Api --urls http://0.0.0.0:5099</code>'
        + '<br>然后访问 <code>http://localhost:5099/admin.html</code></div>'
        + '<div class="bar"><button class="btn pri" onclick="bootstrap()">重试</button></div>'
        + '</div></div>';
    });
}
'''

anchor = "setView('meetings');"
assert s.count(anchor) == 1, '初始化锚点不唯一: %d' % s.count(anchor)
s = s.replace(anchor, BOOT + '\nbootstrap();', 1)
print('[3] 已注入 bootstrap() 并替换初始化入口')

# ---------- switchMeeting：切换会议后重新拉取 ----------
old_sw = """function switchMeeting(id){
  ROLE.meeting=+id; ROLE.dept='all';
  var m=meet();
  toast('已切换会议：'+m.name+(m.depts.length?'（含处室维度）':'（无处分室）'));
  render();
}"""
new_sw = """function switchMeeting(id){
  ROLE.meeting=+id; ROLE.dept='all'; ROLE.matType='doc';
  var m=meet();
  toast('已切换会议：'+m.name+(m.depts.length?'（含处室维度）':'（无处分室）'));
  bootstrap(true);
}"""
if old_sw in s:
    s = s.replace(old_sw, new_sw, 1)
    print('[4] switchMeeting 已改为重新拉取')
else:
    print('   ! switchMeeting 未匹配，跳过')

open(P, 'w', encoding='utf-8').write(s)
print('[5] admin.html %d -> %d bytes' % (before, len(s.encode())))
