#!/usr/bin/env bash
# ── Jarvis 连接 Token 管理器 ──
# 管理 LiveKit JWT Token 生命周期：
#   1. 检查托管仓库 ~/.hermes/jarvis-tokens.json 中是否有未过期 Token
#   2. 有则列出所有有效 Token 及其完整 URL
#   3. 无则生成新 Token（365天），存入仓库后输出

TOKEN_STORE="${HOME}/.hermes/jarvis-tokens.json"

/home/spy/src/Project/livekit-llm-agent/.venv/bin/python -c "
import os, json, sys
from datetime import datetime, timezone, timedelta
from dotenv import load_dotenv
from livekit import api

env_path = '/home/spy/src/Project/livekit-llm-agent/.env'
load_dotenv(env_path)

api_key  = os.getenv('LIVEKIT_API_KEY')
api_secret = os.getenv('LIVEKIT_API_SECRET')
ws_url   = 'wss://www.baboonking.top'
identity = 'arch-coder'
room     = 'jarvis-voice'
ttl_days = 365
store_path = os.path.expanduser('${TOKEN_STORE}')

if not api_key or not api_secret:
    print('错误：.env 中未找到 LIVEKIT_API_KEY 或 LIVEKIT_API_SECRET')
    sys.exit(1)

# ── 加载已有 Token ──
tokens = []
if os.path.exists(store_path):
    with open(store_path) as f:
        try:
            tokens = json.load(f)
        except json.JSONDecodeError:
            tokens = []

now = datetime.now(timezone.utc)
valid = []

for t in tokens:
    try:
        exp = datetime.fromisoformat(t['expires_at'])
        if exp > now:
            valid.append(t)
    except (KeyError, ValueError):
        continue

# ── 输出 ──
print('=' * 60)
print('  Jarvis 语音连接 Token 管理')
print('=' * 60)
print()

if valid:
    print(f'已有 {len(valid)} 个有效 Token：')
    print()
    for i, t in enumerate(valid, 1):
        url = f'https://www.baboonking.top/webapp.html?token={t[\"token\"]}&url={ws_url}'
        print(f'  [{i}] Token:    {t[\"token\"][:40]}...')
        print(f'      创建于:   {t[\"created_at\"]}')
        print(f'      过期于:   {t[\"expires_at\"]}')
        print(f'      链接:     {url}')
        print()
else:
    print('托管仓库中无有效 Token，正在生成新 Token...')
    print()

    token_str = (api.AccessToken(api_key, api_secret)
                 .with_identity(identity)
                 .with_name(identity)
                 .with_grants(api.VideoGrants(room_join=True, room=room, can_publish=True, can_subscribe=True, can_publish_data=True))
                 .with_ttl(timedelta(days=ttl_days))
                 .to_jwt())

    created = datetime.now(timezone.utc)
    exp     = created + timedelta(days=ttl_days)

    entry = {
        'token':       token_str,
        'created_at':  created.isoformat(),
        'expires_at':  exp.isoformat(),
        'identity':    identity,
        'room':        room,
    }

    tokens.append(entry)
    with open(store_path, 'w') as f:
        json.dump(tokens, f, indent=2)

    url = f'https://www.baboonking.top/webapp.html?token={token_str}&url={ws_url}'
    print(f'  Token:    {token_str[:40]}...')
    print(f'  创建于:   {created.isoformat()}')
    print(f'  过期于:   {exp.isoformat()}')
    print(f'  身份:     {identity}')
    print(f'  房间:     {room}')
    print(f'  链接:     {url}')
    print()
    print('  （已保存至 ~/.hermes/jarvis-tokens.json，后续运行将复用此 Token 直至过期）')
    print()

print('=' * 60)
"
