#!/usr/bin/env python3
"""MCP → 工作台数据刷新脚本（活动+客诉+阻塞）"""
import subprocess, json, sys, os
from datetime import datetime
from collections import defaultdict

TK = "m-abfb29e8-3104-434f-9944-8d0bb592f8cd"
SALES_PK = "6593cd71471290e3cc6be6e6"
BASE = os.path.dirname(os.path.abspath(__file__))

DEPT_MAP = {
    '2o467stav': '诊断原料销售部', 'i4l86_tn6': '生命科学-浙江',
    '591s4k2uz': '生命科学-广东', 'sp46mkhje': '大客户部',
    'xnm4v7thp': '未知', 'y23lpl4ex': '未知',
}

def mcp(method, args, timeout=30):
    r = subprocess.run(['curl','-s','-X','POST','https://project.feishu.cn/mcp_server/v1',
        '-H',f'X-Mcp-Token: {TK}','-H','Content-Type: application/json',
        '-d', json.dumps({"jsonrpc":"2.0","method":"tools/call","params":{"name":method,"arguments":args},"id":1})],
        capture_output=True, text=True, timeout=timeout)
    try:
        d = json.loads(r.stdout)
        if 'error' in d: return None
        for c in d['result']['content']:
            t = c.get('text','')
            if 'log_id' in t: continue
            return json.loads(t)
    except: return None
    return None

def parse_items(result):
    items = []
    if not result: return items
    for gid, gitems in result.get('data', {}).items():
        for item in gitems:
            fields = {}
            for f in item.get('moql_field_list', []):
                k = f['name']
                vdict = f.get('value', {})
                vals = list(vdict.values()) if vdict else ['']
                v = vals[0] if vals else ''
                if isinstance(v, dict): v = list(v.values())[0] if v else ''
                fields[k] = str(v) if v else ''
            items.append(fields)
    return items

def query_all(mql):
    all_items = []
    seen = set()
    page = 0
    while page < 150:  # safety cap
        offset = page * 50
        full_mql = f"{mql} LIMIT 50 OFFSET {offset}"
        result = mcp("search_by_mql", {"project_key": SALES_PK, "mql": full_mql})
        if not result: break
        items = parse_items(result)
        if not items: break
        new = []
        for i in items:
            k = (i.get('名称',''), i.get('创建时间',''))
            if k not in seen:
                seen.add(k)
                new.append(i)
        all_items.extend(new)
        page += 1
        if len(items) < 50: break
    return all_items

# 1. Pull activities
print(f"[{datetime.now().strftime('%H:%M:%S')}] 拉取活动数据...")
now = datetime.now()
start = f"{now.year}-01-01"
end = now.strftime('%Y-%m-%d')
MQL = f'SELECT name, description, `创建时间`, `创建者`, `跟进部门`, work_item_id FROM `销售管理`.`活动` WHERE `创建时间` >= "{start}" AND `创建时间` <= "{end}" ORDER BY `创建时间` ASC'
activities = query_all(MQL)
print(f"  活动: {len(activities)}条")

# Load existing creator map
try:
    with open(f"{BASE}/activities_q2q3_2026.json") as f:
        old = json.load(f)
    creator_map = old.get('creator_map', {})
except:
    creator_map = {}

# Resolve new creator IDs
new_creators = set()
for a in activities:
    cid = a.get('创建者', '')
    if cid and cid not in creator_map and cid not in new_creators:
        new_creators.add(cid)

for cid in list(new_creators)[:5]:  # max 5 per run
    for a in activities:
        wid = a.get('工作项id', a.get('work_item_id', ''))
        if a.get('创建者') == cid and wid:
            brief = mcp("get_workitem_brief", {"project_key": SALES_PK, "work_item_id": wid}, timeout=20)
            if brief:
                name = brief.get('work_item_attribute', {}).get('create_by', {}).get('name', '')
                if name:
                    creator_map[cid] = name
            break

# Build output
by_month = defaultdict(lambda: defaultdict(int))
by_dept = defaultdict(int)
for a in activities:
    m = a.get('创建时间', '')[:7]
    d = DEPT_MAP.get(a.get('跟进部门', ''), '未知')
    if m: by_month[m][d] += 1
    by_dept[d] += 1

out = {
    'updated': now.strftime('%Y-%m-%d %H:%M'),
    'period': f'{start} ~ {end}',
    'total': len(activities),
    'by_month': {m: dict(d) for m, d in sorted(by_month.items())},
    'by_dept': dict(sorted(by_dept.items(), key=lambda x: -x[1])),
    'by_creator': {},
    'dept_mapping': DEPT_MAP,
    'creator_map': creator_map,
    'highlights': [],
}

# Top creators
by_creator = defaultdict(int)
for a in activities:
    name = creator_map.get(a.get('创建者', ''), '')
    if name: by_creator[name] += 1
out['by_creator'] = dict(sorted(by_creator.items(), key=lambda x: -x[1])[:20])

# Highlights (non-generic)
dept_acts = defaultdict(list)
for a in activities:
    d = DEPT_MAP.get(a.get('跟进部门', ''), '未知')
    dept_acts[d].append({
        'date': a.get('创建时间', ''),
        'name': a.get('名称', ''),
        'creator': creator_map.get(a.get('创建者', ''), ''),
        'dept': d,
    })

out['highlights'] = [
    {'date': a['date'], 'name': a['name'], 'creator': a['creator'], 'dept': a['dept']}
    for d, acts in dept_acts.items() for a in acts
    if '活动跟进' not in a['name'] and a['name']
][:100]

with open(f"{BASE}/mcp_activities.json", 'w') as f:
    json.dump(out, f, ensure_ascii=False, indent=2)

# 2. 客诉: MQL全量拉取 (pull_complaints.py)
print(f"[{datetime.now().strftime('%H:%M:%S')}] 拉取客诉...")
subprocess.run([sys.executable, f"{BASE}/pull_complaints.py"], cwd=BASE)

# 3. 阻塞: 保留旧管道
print(f"[{datetime.now().strftime('%H:%M:%S')}] 拉取审批阻塞...")
subprocess.run([sys.executable, f"{BASE}/mcp_pipeline.py"], cwd=BASE, capture_output=True)

# Copy blockers to standardized names (complaints 已由 pull_complaints.py 直接输出 mcp_complaints.json)
import shutil
if os.path.exists(f"{BASE}/feishu_blockers.json"):
    shutil.copy(f"{BASE}/feishu_blockers.json", f"{BASE}/mcp_blockers.json")

print(f"[{datetime.now().strftime('%H:%M:%S')}] ✅ 刷新完成")
print(f"  活动: {len(activities)}条")
# 客诉已由 pull_complaints.py 直接输出
