"""Quick test of AnyDesk HMAC-SHA1 auth + live API call"""
import hashlib, hmac, base64, time, asyncio, aiohttp, json

LICENSE_ID = "1543834064287906"
API_TOKEN  = "KQI35S594KAHJS5"
BASE_URL   = "https://v1.api.anydesk.com:8081"

def make_auth(resource, method="GET", content=""):
    sha1 = hashlib.sha1()
    sha1.update(content.encode())
    ch = base64.b64encode(sha1.digest()).decode()
    ts = str(int(time.time()))
    req = f"{method}\n{resource}\n{ts}\n{ch}"
    sig = hmac.new(API_TOKEN.encode(), req.encode(), hashlib.sha1).digest()
    tok = base64.b64encode(sig).decode()
    return f"AD {LICENSE_ID}:{ts}:{tok}"

async def test():
    end = int(time.time())
    start = end - 30 * 86400  # last 30 days
    resource = f"/sessions?from={start}&to={end}&limit=10"
    headers = {"Authorization": make_auth(resource)}
    print(f"URL: GET {BASE_URL}{resource}")
    print(f"Auth: {headers['Authorization'][:70]}...")
    async with aiohttp.ClientSession() as s:
        async with s.get(
            f"{BASE_URL}{resource}",
            headers=headers,
            timeout=aiohttp.ClientTimeout(total=15),
            ssl=True,
        ) as r:
            txt = await r.text()
            print(f"\nStatus: {r.status}")
            print(f"Response:\n{txt[:800]}")
            if r.status == 200:
                try:
                    data = json.loads(txt)
                    sessions = data.get("list", [])
                    print(f"\n✅ OK - {len(sessions)} sessions returned")
                    for s in sessions[:3]:
                        print(f"  sid={s.get('sid')} | from={s.get('from',{}).get('alias','?')} | duration={s.get('duration')}s")
                except Exception as e:
                    print(f"Parse error: {e}")

asyncio.run(test())
