#!/usr/bin/env python3
"""发送销售日报交互式卡片到飞书"""
import json, urllib.request, sys

APP_ID = 'cli_aaee6a2f90b89bc1'
APP_SECRET = 'arht5fd8wyppZysFvOjUcb2bV0UMVVYF'
OPEN_ID = 'ou_901b790c9afdda4a8f14554962b32664'
BRIEF_PATH = '/Users/liuxinyuan/Desktop/Hermes输出-工作类/数据/daily_briefs/latest.md'

# Read latest.md
with open(BRIEF_PATH, 'r') as f:
    content = f.read()

# Get tenant access token
body = json.dumps({'app_id': APP_ID, 'app_secret': APP_SECRET}).encode()
req = urllib.request.Request(
    'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal',
    data=body, headers={'Content-Type': 'application/json'}, method='POST')
with urllib.request.urlopen(req, timeout=10) as resp:
    r = json.loads(resp.read())
if r.get('code') != 0:
    print(f"TOKEN ERROR: {r}", file=sys.stderr)
    sys.exit(1)
token = r['tenant_access_token']
print(f"Token OK: {token[:20]}...")

# Build card: split content into sections and group into <4000 char chunks
sections = content.split('\n\n')
compact_elements = []
current_chunk = ''

for section in sections:
    section = section.strip()
    if not section or section.startswith('---'):
        continue
    if section.startswith('📋 宝锐生物 · 销售日报'):
        continue  # title goes in header
    
    test_len = len(current_chunk) + len(section) + 2
    if test_len > 3800 and current_chunk:
        compact_elements.append({
            'tag': 'div',
            'text': {'tag': 'lark_md', 'content': current_chunk.strip()}
        })
        current_chunk = section
    else:
        current_chunk = (current_chunk + '\n\n' + section) if current_chunk else section

if current_chunk:
    compact_elements.append({
        'tag': 'div',
        'text': {'tag': 'lark_md', 'content': current_chunk.strip()}
    })

# Add footer with links
footer = '\n\n---\n[📊 打开工作台](https://bier-sales-6gilsvtp0e5cc973-1371818483.tcloudbaseapp.com/workbench/index.html) | [📋 飞书销售管理](https://project.feishu.cn/xsguanli/story/homepage)'
compact_elements.append({
    'tag': 'div',
    'text': {'tag': 'lark_md', 'content': footer}
})

# Cap at 20 elements (Feishu limit: 50)
if len(compact_elements) > 20:
    compact_elements = compact_elements[:20]

card = {
    'config': {'wide_screen_mode': True},
    'header': {
        'title': {'tag': 'plain_text', 'content': '📋 销售日报'},
        'template': 'blue'
    },
    'elements': compact_elements
}

card_json = json.dumps(card, ensure_ascii=False)
print(f"Card: {len(compact_elements)} elements, {len(card_json)} chars")

# Send message
msg = json.dumps({
    'receive_id': OPEN_ID,
    'msg_type': 'interactive',
    'content': card_json
}).encode('utf-8')

req = urllib.request.Request(
    'https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id',
    data=msg,
    headers={
        'Content-Type': 'application/json',
        'Authorization': f'Bearer {token}'
    },
    method='POST'
)

try:
    with urllib.request.urlopen(req, timeout=15) as resp:
        r = json.loads(resp.read())
    
    if r.get('code') == 0:
        msg_id = r.get('data', {}).get('message_id', 'unknown')
        print(f"SUCCESS: message_id={msg_id}")
    else:
        print(f"FAILED: code={r.get('code')}, msg={r.get('msg')}")
        sys.exit(1)
except Exception as e:
    print(f"HTTP ERROR: {e}", file=sys.stderr)
    sys.exit(1)
