# -*- coding: utf-8 -*-
"""探针：验证 search_by_mql 对「客户」表的可翻页方式。
目的：确认 1050 行是 OFFSET 上限导致，并找出能拉全量（1761 条）的翻页路径。
"""
import json
import subprocess

TK = "m-abfb29e8-3104-434f-9944-8d0bb592f8cd"
PK = "6593cd71471290e3cc6be6e6"
COLUMNS = ('name, field_c3224b, field_5ed7ab, field_c8e80d, field_17186c, field_8c870a, '
           'field_79aa0b, field_6415cf, work_item_id, field_e62869, owner, current_status_operator')


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


def rows_of(res):
    out = []
    data = (res or {}).get('data')
    groups = list(data.values()) if isinstance(data, dict) else (data or [])
    for g in groups:
        if isinstance(g, dict):
            g = g.get('moql_field_list') or []
        if not isinstance(g, list):
            continue
        for item in g:
            if isinstance(item, dict) and item.get('moql_field_list'):
                out.append(item)
    return out


mql = "SELECT %s FROM `销售管理`.`客户` ORDER BY name ASC LIMIT 50" % COLUMNS
res = mcp('search_by_mql', {'project_key': PK, 'mql': mql})
print('首页 ok:', bool(res))
if res:
    print('  session_id:', res.get('session_id'))
    print('  list[0].count:', (res.get('list') or [{}])[0].get('count'))
    print('  group_infos:', (res.get('list') or [{}])[0].get('group_infos'))
    print('  首页行数:', len(rows_of(res)))
    print('  data keys:', list((res.get('data') or {}).keys())[:5])
    print('  res top keys:', list(res.keys()))
