#!/usr/bin/env python3
"""联系人数据拉取 — 按客户聚合联系人名称
用法: python3 pull_contacts.py
输出: customer_contacts.json  {客户名: [联系人名称列表]}
"""
import subprocess, json, os
from datetime import datetime
from collections import defaultdict

TK = "m-abfb29e8-3104-434f-9944-8d0bb592f8cd"
PK = "6593cd71471290e3cc6be6e6"
BASE = os.path.dirname(os.path.abspath(__file__))
OUTPUT = os.path.join(BASE, "customer_contacts.json")

def mcp(method, args):
    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=30)
    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

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['key']
                v = f.get('value')
                if v is None: fields[k] = ''
                elif 'string_value' in v: fields[k] = v['string_value']
                elif 'long_value' in v: fields[k] = v['long_value']
                elif 'key_label_value' in v: fields[k] = v['key_label_value']
                elif 'key_label_value_list' in v: fields[k] = v['key_label_value_list']
                else: fields[k] = ''
            items.append(fields)
    return items

by_customer = defaultdict(list)
seen = set()
page = 0
print(f"[{datetime.now().strftime('%H:%M:%S')}] 拉取联系人数据...")
while page < 200:
    offset = page * 50
    mql = f"SELECT name, field_6b3789, work_item_id FROM `销售管理`.`联系人` ORDER BY name ASC LIMIT 50 OFFSET {offset}"
    result = mcp("search_by_mql", {"project_key": PK, "mql": mql})
    if not result: break
    items = parse_items(result)
    if not items: break
    for item in items:
        wid = str(item.get('work_item_id', ''))
        if wid in seen: continue
        seen.add(wid)
        name = item.get('name', '')
        if not name: continue
        customer = item.get('field_6b3789', '')
        if isinstance(customer, dict):
            customer = customer.get('label', '')
        if customer:
            by_customer[customer].append(name)
    page += 1
    if len(items) < 50: break
    if page % 20 == 0:
        print(f"  page {page}: {len(seen)} contacts, {len(by_customer)} customers")

print(f"  共 {len(seen)} 联系人, {len(by_customer)} 个客户有关联联系人")

std = {
    'updated': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
    'total_contacts': len(seen),
    'customers_with_contacts': len(by_customer),
    'contacts': dict(by_customer),
}

with open(OUTPUT, 'w', encoding='utf-8') as f:
    json.dump(std, f, ensure_ascii=False)

print(f"✅ 写入 {OUTPUT}")
