#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""P2-P1 后端：/api/visit/stats 支持 scope(me|team) + 近 12 月 trend。

Q2 决定：销售=自己 / 管理者=全队。管理者可切，销售强制 me（服务端兜底，不信前端）。
"""
import io
import os
import shutil
import sys
import time

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

START = '        # ══════════ P1：拜访视图统计（当月线下拜访次数 / 线上跟进次数）══════════'
END = '        # ══════════ 活动录入：订单 / SKU / 列表 / 详情 / 附件地址 ══════════'

NEW = '''        # ══════════ 拜访与活动统计（当月线下拜访次数 / 线上跟进次数 + 近 12 月趋势）══════════
        # scope=me|team；team 仅 admin/gm/manager 可用，其余强制 me（服务端兜底，不信前端）
        if path == '/api/visit/stats':
            _au = self._auth_user()
            if not _au:
                self._send_json({'ok': False, 'error': '登录已过期，请重新登录'}, 401)
                return
            from urllib.parse import parse_qs
            _qs = {k: v[0] for k, v in parse_qs(self.path.split('?', 1)[1]).items()} if '?' in self.path else {}
            month = ((_qs.get('month') or '').strip() or datetime.now().strftime('%Y-%m'))[:7]
            if not re.match(r'^\\d{4}-\\d{2}$', month):
                self._send_json({'ok': False, 'error': 'month 需为 YYYY-MM'}, 400)
                return
            _role = _au.get('role')
            _allow_team = _role in ('admin', 'gm', 'manager')
            scope = (_qs.get('scope') or '').strip().lower()
            if scope not in ('me', 'team'):
                scope = 'team' if _allow_team else 'me'
            if scope == 'team' and not _allow_team:
                scope = 'me'
            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':
                _me = _au.get('name') or ''
                rows = [x for x in rows if x.get('submitted_by') == _me or x.get('sales') == _me]
            monthly = [x for x in rows if (x.get('date') or '').startswith(month)]
            offline = online = noclass = 0
            cust = {}
            for x in monthly:
                ch = (x.get('channel') or '').strip()
                if ch == 'offline':
                    offline += 1
                elif ch == 'online':
                    online += 1
                else:
                    noclass += 1
                c = (x.get('customer') or '').strip() or '(未填客户)'
                d = cust.setdefault(c, {'customer': c, 'offline': 0, 'online': 0, 'other': 0, 'acts': []})
                d['offline' if ch == 'offline' else ('online' if ch == 'online' else 'other')] += 1
                d['acts'].append({'id': x.get('id', ''), 'date': x.get('date', ''), 'channel': ch,
                                  'type': x.get('type', ''), 'sales': x.get('sales', '')})
            for d in cust.values():
                d['total'] = d['offline'] + d['online'] + d['other']
                d['acts'].sort(key=lambda a: a.get('date') or '', reverse=True)
            # 近 12 个月趋势（同一权限与 scope 口径）
            allm = sorted({(x.get('date') or '')[:7] for x in rows if x.get('date')})
            trend = []
            for m in allm[-12:]:
                mm = [x for x in rows if (x.get('date') or '').startswith(m)]
                trend.append({'month': m,
                              'offline': sum(1 for x in mm if (x.get('channel') or '') == 'offline'),
                              'online': sum(1 for x in mm if (x.get('channel') or '') == 'online'),
                              'total': len(mm)})
            self._send_json({'ok': True, 'month': month, 'scope': scope, 'can_team': _allow_team,
                             'offline_count': offline, 'online_count': online,
                             'unclassified': noclass, 'total': len(monthly),
                             'customer_count': len(cust), 'months': allm[-12:], 'trend': trend,
                             'customers': sorted(cust.values(), key=lambda d: -d['total'])})
            return

'''


def main():
    apply = '--apply' in sys.argv
    s = io.open(F, encoding='utf-8').read()
    i = s.find(START)
    j = s.find(END, i)
    print('P2-P1 后端补丁 —— %s' % ('APPLY' if apply else 'DRY-RUN'))
    if i < 0 or j < 0:
        print('  ❌ 区间未找到 (start=%d end=%d)' % (i, j))
        return 1
    old = s[i:j]
    print('  ✅ 命中区间 %d 字符（旧实现）→ 新实现 %d 字符' % (len(old), len(NEW)))
    out = s[:i] + NEW + s[j:]
    if apply:
        ts = time.strftime('%Y%m%d-%H%M%S')
        bak = os.path.join(ROOT, '_bak_p2_visitapi_%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(out)
        print('  已写（备份 %s）' % bak)
    else:
        print('  干跑通过，未落盘。')
    return 0


sys.exit(main())
