#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""后端：把飞书历史活动（只读基础数据）并入拜访与活动统计，并支持 FS* 活动详情。"""
import io
import os
import shutil
import sys
import time

ROOT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类'
F = os.path.join(ROOT, '脚本', '销售工作台服务.py')

HELPER_ANCHOR = 'def _act_sync_todos(rec, confirmed, draft_id):'
HELPER = '''FEISHU_ACT_FILE = os.path.join(DATA_DIR, 'activities_feishu.json')
_FS_ACT = {'data': None, 'mtime': None, 'idx': {}}


def _feishu_act_rows():
    """飞书历史活动（只读基础数据，由 脚本/build_feishu_activities.py 生成）。按 mtime 缓存。"""
    try:
        mt = os.path.getmtime(FEISHU_ACT_FILE)
    except OSError:
        return []
    if _FS_ACT['data'] is None or _FS_ACT['mtime'] != mt:
        try:
            with open(FEISHU_ACT_FILE, encoding='utf-8') as f:
                d = json.load(f)
            rows = d.get('items') or []
            _FS_ACT['data'] = rows
            _FS_ACT['idx'] = {r.get('id'): r for r in rows}
            _FS_ACT['mtime'] = mt
        except Exception:
            return []
    return _FS_ACT['data']


def _feishu_act_one(fid):
    _feishu_act_rows()
    return _FS_ACT['idx'].get(fid)


'''

MERGE_OLD = """            vis = _act_visible_sales(_au)
            rows = [x for x in _act_load_index()
                    if vis is None or (x.get('submitted_by') in vis) or (x.get('sales') in vis)]
            if scope == 'me':"""
MERGE_NEW = """            vis = _act_visible_sales(_au)
            _wts = _act_load_index()
            _fsh = _feishu_act_rows()
            rows = [x for x in (_wts + _fsh)
                    if vis is None or (x.get('submitted_by') in vis) or (x.get('sales') in vis)]
            if scope == 'me':"""

RESP_OLD = "                             'departments': groups, 'dept_count': len(groups),"
RESP_NEW = ("                             'departments': groups, 'dept_count': len(groups),\n"
            "                             'src_breakdown': {\n"
            "                                 'workbench': len([x for x in monthly if x.get('src') != 'feishu']),\n"
            "                                 'feishu': len([x for x in monthly if x.get('src') == 'feishu'])},\n"
            "                             'channel_judge': {\n"
            "                                 'judged': offline + online, 'unknown': noclass,\n"
            "                                 'rate': round((offline + online) * 100.0 / max(len(monthly), 1), 1)},")

DET_OLD = """            if path == '/api/activity/detail':
                rid = os.path.basename((_qs.get('id') or '').strip())
                try:"""
DET_NEW = """            if path == '/api/activity/detail':
                rid = os.path.basename((_qs.get('id') or '').strip())
                if rid.startswith('FS'):        # 飞书历史活动（只读基础数据，不在本地文件里）
                    _fr = _feishu_act_one(rid)
                    if not _fr:
                        self._send_json({'ok': False, 'error': '未找到该飞书活动'}, 404)
                        return
                    _ow = (_fr.get('submitted_by') or '').strip()
                    _vis = _act_visible_sales(_au)
                    if _vis is not None and _ow not in _vis:
                        self._send_json({'ok': False, 'error': '无权查看该活动'}, 403)
                        return
                    _ch = {'offline': '线下拜访', 'online': '线上跟进'}.get(_fr.get('channel'), '未标形式')
                    _ev = _fr.get('channel_ev') or []
                    self._send_json({'ok': True, 'activity': {
                        'id': rid, 'src': 'feishu', 'date': _fr.get('date', ''),
                        'customer': _fr.get('customer', ''), 'sales': _ow, 'submitted_by': _ow,
                        'channel': _fr.get('channel', ''), 'channel_ev': _ev,
                        'type': _fr.get('type', ''), 'order_ref_nos': [],
                        'feishu_text': ('【来源】飞书历史活动（基础数据 · 只读）\\n【日期】%s\\n【客户】%s\\n'
                                        '【归属】%s\\n【活动名称】%s\\n【活动形式】%s%s\\n\\n【活动描述】\\n%s'
                                        % (_fr.get('date', ''), _fr.get('customer') or '—', _ow,
                                           _fr.get('type') or '—', _ch,
                                           ('（文本依据：%s）' % '、'.join(_ev)) if _ev else '',
                                           _fr.get('text') or ''))}})
                    return
                try:"""


def main():
    apply = '--apply' in sys.argv
    s = io.open(F, encoding='utf-8').read()
    print('飞书基础数据并入 —— %s\n' % ('APPLY' if apply else 'DRY-RUN'))
    ok = True
    for label, old, new in [('A 加载器', HELPER_ANCHOR, HELPER + HELPER_ANCHOR),
                            ('B 统计合并', MERGE_OLD, MERGE_NEW),
                            ('C 响应加来源/可判定率', RESP_OLD, RESP_NEW),
                            ('D 详情支持 FS*', DET_OLD, DET_NEW)]:
        n = s.count(old)
        print('  %s %-22s 命中 %d' % ('✅' if n == 1 else '❌', label, n))
        if n != 1:
            ok = False
        else:
            s = s.replace(old, new, 1)
    if not ok:
        print('\n有未命中 → 不落盘')
        return 1
    if apply:
        ts = time.strftime('%Y%m%d-%H%M%S')
        bak = os.path.join(ROOT, '_bak_p2c_feishu_%s' % ts)
        os.makedirs(bak, exist_ok=True)
        shutil.copy2(F, os.path.join(bak, os.path.basename(F)))
        io.open(F, 'w', encoding='utf-8').write(s)
        print('\n  已写（备份 %s）' % bak)
    else:
        print('\n  干跑通过，未落盘。')
    return 0


sys.exit(main())
