import json,re,datetime
from pathlib import Path
import requests

WS=Path('/Users/ahmad/.openclaw/workspace')
TOKEN=re.search(r'(pk_[A-Za-z0-9_]+)',(WS/'clickup_credentials.md').read_text()).group(1)
H={'Authorization':TOKEN}
B='https://api.clickup.com/api/v2'

def get(u,p=None):
    r=requests.get(u,headers=H,params=p,timeout=60)
    r.raise_for_status(); return r.json()

def list_tasks(list_id):
    out=[];page=0
    while True:
        d=get(f'{B}/list/{list_id}/task',{'page':page,'include_closed':'true','subtasks':'true'})
        t=d.get('tasks',[])
        out.extend(t)
        if not t or d.get('last_page') is True: break
        page+=1
        if page>300: break
    return out

stamp=datetime.datetime.now().strftime('%Y%m%d_%H%M')
dir=WS/'clickup_restructure_backup'/stamp
dir.mkdir(parents=True,exist_ok=True)

teams=get(f'{B}/team').get('teams',[])
team=teams[0]
spaces=get(f"{B}/team/{team['id']}/space",{'archived':'false'}).get('spaces',[])
folders=[];lists=[];tasks={}
for s in spaces:
    sid=s['id']
    fl=get(f'{B}/space/{sid}/folder',{'archived':'false'}).get('folders',[])
    folders.extend(fl)
    s_lists=get(f'{B}/space/{sid}/list',{'archived':'false'}).get('lists',[])
    for l in s_lists:
        lists.append(l)
        tasks[l['id']]=list_tasks(l['id'])
    for f in fl:
        f_lists=get(f"{B}/folder/{f['id']}/list",{'archived':'false'}).get('lists',[])
        for l in f_lists:
            lists.append(l)
            tasks[l['id']]=list_tasks(l['id'])

(dir/'team.json').write_text(json.dumps(team,indent=2))
(dir/'spaces.json').write_text(json.dumps(spaces,indent=2))
(dir/'folders.json').write_text(json.dumps(folders,indent=2))
(dir/'lists.json').write_text(json.dumps(lists,indent=2))
(dir/'tasks_by_list.json').write_text(json.dumps(tasks,indent=2))

print(json.dumps({'snapshot_dir':str(dir),'spaces':len(spaces),'lists':len(lists)},indent=2))
