#!/usr/bin/env python3
"""Upload one completed session or a BeatAI exported JSON file."""
import argparse, hashlib, json, urllib.request, uuid
from pathlib import Path
p=argparse.ArgumentParser(description='上传 BeatAI 战绩到 tokburn.com')
p.add_argument('--url',default='https://tokburn.com');p.add_argument('--ai',choices=['openai','claude','zhipu','kimi','deepseek','grok','grop','gemini']);p.add_argument('--anger',type=int);p.add_argument('--hits',type=int);p.add_argument('--id',help='固定的战绩编号，重试时使用相同编号');p.add_argument('--file',type=Path,help='BeatAI 导出的 JSON');p.add_argument('--state',type=Path,default=Path.home()/'.tokbure-upload.json',help='本机已上传计数记录')
a=p.parse_args(); state=json.loads(a.state.read_text()) if a.state.exists() else {}
def send(d):
    req=urllib.request.Request(a.url.rstrip('/')+'/api/submissions',data=json.dumps(d).encode(),headers={'Content-Type':'application/json'})
    with urllib.request.urlopen(req,timeout=20) as r: print(json.loads(r.read())['message'])
if a.file:
    d=json.loads(a.file.read_text());aliases={'openai':'openai','chatgpt':'openai','claude':'claude','zhipu':'zhipu','智谱':'zhipu','glm':'zhipu','kimi':'kimi','deepseek':'deepseek','grok':'grok','grop':'grok','gemini':'gemini'}
    for profile in d.get('profiles',[]):
        ai=next((v for k,v in aliases.items() if k in profile['name'].lower()),None)
        if not ai: print('跳过未匹配的 AI：'+profile['name']);continue
        key=profile['id']+':'+ai;total=profile['hits'];delta=total-state.get(key,0)
        if delta<=0: print('没有新增记录：'+profile['name']);continue
        send({'ai':ai,'anger':delta,'hits':delta,'submissionId':'beatai:'+key+':'+str(total)})
        state[key]=total;a.state.write_text(json.dumps(state))
else:
    if not a.ai or not a.anger: p.error('请提供 --ai 和 --anger，或 --file')
    sid=a.id or str(uuid.uuid4());print('战绩编号（重试时请使用 --id）：'+sid)
    send({'ai':a.ai,'anger':a.anger,'hits':a.hits if a.hits is not None else a.anger,'submissionId':sid})
