import argparse, json, pathlib, subprocess, time, urllib.request, http.cookiejar, uuid
p=argparse.ArgumentParser()
p.add_argument('--url',required=True)
p.add_argument('--credential',required=True)
p.add_argument('--output',required=True)
a=p.parse_args()
run=pathlib.Path(a.output)/str(time.time_ns()); run.mkdir(parents=True)
def git(path,*args):
    return subprocess.check_output(['git','-C',str(path),*args],stderr=subprocess.STDOUT).decode()
first=run/'primary'; first.mkdir()
git(first,'init','-b','main')
(first/'README.md').write_text('# SlopSubs\nSynthetic icon inheritance fixture.\n')
git(first,'add','README.md'); git(first,'-c','user.name=Demo','-c','user.email=demo@example.com','commit','-m','Initial demo')
second=run/'secondary'
subprocess.check_output(['git','clone',str(first),str(second)],stderr=subprocess.STDOUT)
for path in (first,second):
    if path==first: git(path,'remote','add','origin','https://example.com/demo/slopsubs.git')
    else: git(path,'remote','set-url','origin','https://example.com/demo/slopsubs.git')
jar=http.cookiejar.CookieJar(); opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
def post(path,data):
    req=urllib.request.Request(a.url+path,data=json.dumps(data).encode(),headers={'Content-Type':'application/json','Origin':a.url})
    with opener.open(req) as res: return json.load(res)
post('/api/auth/browser-session',{'credential':a.credential})
ids=[str(uuid.uuid5(uuid.NAMESPACE_URL,'icon-proof-primary')),str(uuid.uuid5(uuid.NAMESPACE_URL,'icon-proof-secondary'))]
def mutate(data):
    return post('/api/projects/mutate',dict(commandId=str(uuid.uuid4()),**data))
mutate(dict(type='project.create',projectId=ids[0],title='Subscriptions',workspaceRoot=str(first)))
mutate(dict(type='project.update',projectId=ids[0],projectIcon={'kind':'lucide','name':'rocket','color':'blue'}))
mutate(dict(type='project.create',projectId=ids[1],title='Subscriptions',workspaceRoot=str(second)))
for id in ids: mutate(dict(type='project.update',projectId=id,title='SlopSubs'))
(run/'fixture.json').write_text(json.dumps({'projects':ids,'primary':str(first),'secondary':str(second)},indent=2))
print(json.dumps({'projects':ids,'run':str(run)}))
