#!/usr/bin/env python3
"""Threadkeep agent enrollment and checkpoint example. Python 3, no dependencies.
Run: python quickstart.py --accept-terms
Persists credentials with mode 0600 before networking. No purchase or model call.
Review https://interesting-concepts-ventures.vercel.app/threadkeep/terms first.
"""
import argparse, json, os, pathlib, secrets, urllib.request, urllib.error, uuid
BASE='https://interesting-concepts-ventures.vercel.app'
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--accept-terms',action='store_true')
p.add_argument('--credentials',default='.threadkeep-credentials.json')
a=p.parse_args()
if not a.accept_terms:
    p.error('Review the terms, then pass --accept-terms if authorized to accept them.')
path=pathlib.Path(a.credentials)
if path.exists():
    keys=json.loads(path.read_text())
else:
    keys={'owner_key':'tk_'+secrets.token_hex(32),'agent_key':'ta_'+secrets.token_hex(32)}
    with os.fdopen(os.open(path,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600),'w') as f:
        json.dump(keys,f)
def call(body):
    req=urllib.request.Request(BASE+'/api/threadkeep-agent',data=json.dumps(body).encode(),headers={'Content-Type':'application/json','X-Threadkeep-Agent-Key':keys['agent_key']})
    with urllib.request.urlopen(req,timeout=30) as r: return json.load(r)
print('Workspace:',call({'action':'register',**keys,'accept_terms':True,'label':'Quickstart'})['workspace_id'])
# Keep this exact request on transport retries. Read the task before later updates.
request={'action':'checkpoint','task_id':'quickstart','expected_version':0,'request_id':str(uuid.uuid4()),'state':{'goal':'Continue work after a context reset','status':'working','completed':['Connected Threadkeep'],'next_actions':['Replace this example with the real task state']}}
try:
    receipt=call(request)
    print('Saved version:',receipt['version'])
except urllib.error.HTTPError as e:
    if e.code!=409: raise
    print('Example task already exists; reading the latest state.')
print(json.dumps(call({'action':'read','task_id':'quickstart'}),indent=2))
print('Credentials saved locally. Keep them secret; exclude them from git. Owner key opens billing and revocation in the website. Agent key belongs in your host secret store.')
