from pathlib import Path
import json,subprocess,sys
root=Path(sys.argv[1]);plan=Path(sys.argv[2]);host=sys.argv[3]
def git(*args):return subprocess.check_output(['git','-C',str(root),*args],text=True).strip()
assert git('rev-parse','main')=='38da0adf8c009498a28e779f20749e5a839b8ff8'
items=[i for i in json.loads(plan.read_text())['branches'] if i['host']==host]
remote_tags={}
for line in git('ls-remote','--tags','origin','archive/*').splitlines():
    commit,ref=line.split();remote_tags[ref]=commit
# Preflight every deletion before any ref mutation.
for item in items:
    if item['action']=='keep_unmerged':continue
    assert git('rev-parse','refs/heads/'+item['branch'])==item['commit']
    if item['archive_tag']:
        tag=item['archive_tag'];assert git('cat-file','-t',tag)=='tag'
        assert git('rev-parse',tag+'^{commit}')==item['commit']
        assert remote_tags.get('refs/tags/'+tag+'^{}')==item['commit']
    else:
        subprocess.run(['git','-C',str(root),'merge-base','--is-ancestor',item['commit'],'main'],check=True)
worktrees=[]
for block in git('worktree','list','--porcelain').split('\n\n'):
    values=dict(line.split(' ',1) for line in block.splitlines() if ' ' in line)
    worktrees.append(values)
for item in items:
    if item['action']=='keep_unmerged':continue
    for tree in worktrees:
        if tree.get('branch')!='refs/heads/'+item['branch']:continue
        path=tree['worktree']
        assert not subprocess.check_output(['git','-C',path,'status','--porcelain','--untracked-files=no'],text=True).strip(), 'Dirty worktree: '+path
        assert subprocess.check_output(['git','-C',path,'rev-parse','HEAD'],text=True).strip()==item['commit']
        subprocess.run(['git','-C',path,'switch','--detach',item['commit']],check=True)
    flag='-D' if item['archive_tag'] else '-d'
    subprocess.run(['git','-C',str(root),'branch',flag,item['branch']],check=True)
print('Remaining branches:',git('branch','--format=%(refname:short)'))
