#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""用巨潮 topSearch 接口标注客户上市状态与证券代码（权威源，避免让外部工具猜）。

输出：数据/market_intel/客户上市状态_2026-10-13.json
"""
import json
import os
import re
import time

import requests

UA = ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 '
      '(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36')
API = 'http://www.cninfo.com.cn/new/information/topSearch/query'
OUT = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/数据/market_intel/客户上市状态_2026-10-13.json'
SRC = os.path.expanduser('~/.hermes/profiles/baorui-sales/customer_attribution.json')

SRC = os.path.expanduser('~/.hermes/profiles/baorui-sales/customer_attribution.json')
cust = json.load(open(SRC, encoding='utf-8'))['salespeople']['刘子研']['customers']

# 查询关键词（公司全称里带集团/子公司的，用主体名试探）
def keys(name):
    base = re.sub(r'[（(].*?[)）]', '', name)
    base = re.sub(r'(集团|股份有限公司|有限公司|生物科技|生物技术|科技有限公司|技术有限公司)$', '', base)
    out = [name, base]
    if '集团' in name:
        out.append(name.replace('集团', ''))
    return list(dict.fromkeys([k for k in out if k]))

s = requests.Session()
s.headers.update({'User-Agent': UA, 'X-Requested-With': 'XMLHttpRequest',
                  'Referer': 'http://www.cninfo.com.cn/'})
res = {}
for name in cust:
    found = []
    for k in keys(name):
        try:
            r = s.post(API, data={'keyWord': k, 'maxNum': 10}, timeout=20)
            j = r.json()
        except Exception as e:
            j = None
        if isinstance(j, list):
            for it in j:
                if isinstance(it, dict) and it.get('code'):
                    found.append({'查询词': k, '代码': it.get('code'), '简称': it.get('zwjc'),
                                  'orgId': it.get('orgId'), '类别': it.get('category')})
            if found:
                break
        time.sleep(1.0)
    res[name] = {'上市': bool(found), '匹配': found[:3]}
    mark = found[0]['代码'] + ' ' + str(found[0]['简称']) if found else '未匹配（未上市/简称不符）'
    print('  %-38s → %s' % (name, mark))
    time.sleep(1.0)

json.dump(res, open(OUT, 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
n = sum(1 for v in res.values() if v['上市'])
print('\n合计：%d 家匹配到上市主体 / 共 %d 家' % (n, len(res)))
print('→', OUT)
