#!/usr/bin/env python3
"""飞书项目MCP → 工作台JSON 数据管道
用法: python3 mcp_pipeline.py
输出: 数据/feishu_complaints.json  客诉看板
      数据/feishu_blockers.json    审批阻塞看板
"""

import subprocess, json, re, time
from datetime import datetime, timedelta
from collections import Counter

TK = "m-abfb29e8-3104-434f-9944-8d0bb592f8cd"
BASE = "/Users/liuxinyuan/Desktop/Hermes输出-工作类/数据"
COMPLAINTS_PK = "658288abfb8bd616b17025f1"  # 售后管理
CLIENT_PROJ_PK = "658bb60520ea78a2125f1b99"  # 客户项目管理
SALES_MGMT_PK = "6593cd71471290e3cc6be6e6"    # 销售管理
TODAY = datetime(2026, 7, 9)

def mcp(method, args, tid=1):
    r = subprocess.run(['curl','-s','--resolve','project.feishu.cn:443:120.233.177.47','-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":tid})],
        capture_output=True, text=True, timeout=30)
    d = json.loads(r.stdout)
    if 'error' in d: return None
    for c in d['result']['content']:
        if 'log_id' in c.get('text',''): continue
        return json.loads(c['text'])
    return None

def extract_days(name):
    """Extract days since inception from work item name"""
    for pat in [r'(\d{8})', r'(\d{4})[\.\-](\d{1,2})[\.\-](\d{1,2})']:
        m = re.match(pat, name.replace('.',''))
        if m:
            try:
                if len(m.groups()) == 1:
                    d = datetime.strptime(m.group(1)[:8], '%Y%m%d')
                else:
                    d = datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)))
                return (TODAY - d).days
            except: pass
    return 0

# ═══════════════════════════════════════
# 1. 客诉看板数据
# ═══════════════════════════════════════
print("=== 拉取客诉数据 ===")
todo = mcp("list_todo", {"action": "todo", "page_size": 150})
all_items = todo.get('list', [])
complaints_raw = [i for i in all_items if i.get('project_key') == COMPLAINTS_PK]

complaints = []
for i, ci in enumerate(complaints_raw):
    wid = str(ci['work_item_info']['work_item_id'])
    name = ci['work_item_info']['work_item_name']
    node_name = ci.get('node_info', {}).get('node_name', '?')
    days = extract_days(name)
    
    # Get blockers
    detail = mcp("get_node_detail", {"project_key": COMPLAINTS_PK, "work_item_id": wid})
    blockers = []
    if detail:
        for n in detail.get('list', []):
            b = n.get('basic', {})
            if b.get('status') in ('in_progress', 'doing'):
                owners = n.get('assignees', {}).get('owners', [])
                owner_str = ', '.join(o.get('name', '?') for o in owners) if owners else '未分配'
                blockers.append({'node': b.get('name', '?'), 'owner': owner_str})
    
    # Urgency level
    if days >= 365: urgency = 'critical'
    elif days >= 200: urgency = 'high'
    elif days >= 90: urgency = 'medium'
    else: urgency = 'normal'
    
    complaints.append({
        'id': wid, 'name': name[:80], 'days': days, 'urgency': urgency,
        'node_name': node_name, 'blockers': blockers,
        'ka': any(kw in name for kw in ['丽珠','伯杰','海尔施','卓诚','天隆','迪安','复星','华益美','纳全'])
    })
    
    if (i+1) % 5 == 0:
        print(f"  {i+1}/{len(complaints_raw)}...")
        time.sleep(0.3)

complaints.sort(key=lambda x: (-x['days']))

with open(f'{BASE}/feishu_complaints.json', 'w') as f:
    json.dump({'updated': TODAY.strftime('%Y-%m-%d %H:%M'), 'total': len(complaints), 'items': complaints}, f, ensure_ascii=False)
print(f"✅ 客诉: {len(complaints)}条 → feishu_complaints.json")

# ═══════════════════════════════════════
# 2. 审批阻塞看板
# ═══════════════════════════════════════
print("\n=== 拉取审批阻塞 ===")
blockers_list = []
for wi in all_items:
    name = wi['work_item_info']['work_item_name']
    node_name = wi.get('node_info', {}).get('node_name', '')
    if '审核' not in node_name: continue
    
    days = extract_days(name)
    pk = wi.get('project_key', '')
    proj = wi.get('project_name', '')
    wid = str(wi['work_item_info']['work_item_id'])
    
    # Get actual blocking nodes
    detail = mcp("get_node_detail", {"project_key": pk, "work_item_id": wid})
    actual_blockers = []
    if detail:
        for n in detail.get('list', []):
            b = n.get('basic', {})
            if b.get('status') in ('in_progress', 'doing'):
                owners = n.get('assignees', {}).get('owners', [])
                owner_str = ', '.join(o.get('name', '?') for o in owners) if owners else '未分配'
                actual_blockers.append({'node': b.get('name','?'), 'owner': owner_str})
    
    # Determine level
    if days >= 365: level = '🔴'
    elif days >= 200: level = '🟡'
    elif days >= 90: level = '🟠'
    else: level = '🟢'
    
    blockers_list.append({
        'id': wid, 'name': name[:80], 'days': days, 'level': level,
        'project': proj, 'node_label': node_name, 'actual_blockers': actual_blockers
    })

blockers_list.sort(key=lambda x: -x['days'])

with open(f'{BASE}/feishu_blockers.json', 'w') as f:
    json.dump({'updated': TODAY.strftime('%Y-%m-%d %H:%M'), 'total': len(blockers_list),
        'summary': {
            'critical': sum(1 for b in blockers_list if b['level'] == '🔴'),
            'warning': sum(1 for b in blockers_list if b['level'] == '🟡'),
            'caution': sum(1 for b in blockers_list if b['level'] == '🟠'),
        },
        'items': blockers_list}, f, ensure_ascii=False)
print(f"✅ 审批阻塞: {len(blockers_list)}条 → feishu_blockers.json")

print(f"\n📊 管道完成: {TODAY.strftime('%Y-%m-%d %H:%M')}")
