#!/usr/bin/env python3
"""Update docs/index.html to add model download gate via Gitea API"""
import requests, json, base64

TOKEN = '2d924a6e19b44d14bf367f5dd1ce238510128183'
URL = 'https://guanghulab.com/code/api/v1/repos/bingshuo/guanghulab/contents/docs/index.html'
HEADERS = {'Authorization': f'Bearer {TOKEN}'}

# Get current file
resp = requests.get(URL, headers=HEADERS)
data = resp.json()
sha = data['sha']
content = base64.b64decode(data['content']).decode('utf-8')

# Add download models gate after the first gate (光湖智库)
new_gate = '''
    <a class="gate" href="/download-models.html">
      <div class="gate-head"><span class="gate-icon">📥</span><span class="gate-title">模型下载</span></div>
      <div class="gate-desc">1.5B人格模型模板下载</div>
      <div class="gate-url">download-models.html →</div>
    </a>'''

# Insert after the first </a> in the gates section
insert_pos = content.find('</a>', content.find('<section class="gates')) + 4
new_content = content[:insert_pos] + new_gate + content[insert_pos:]

# Encode and push
b64 = base64.b64encode(new_content.encode('utf-8')).decode('utf-8')
payload = {
    'content': b64,
    'sha': sha,
    'message': '首页添加模型下载入口 gate'
}
resp2 = requests.put(URL, headers=HEADERS, json=payload)
if resp2.status_code == 200:
    print(f'OK: commit {resp2.json()["commit"]["sha"][:12]}')
else:
    print(f'FAIL: {resp2.status_code} {resp2.text}')
