"""Synthetic Azure PR fixture. Load the test Azure environment, then pass an output directory.
Run again with --cleanup to abandon the PRs and delete this fixture's branches.
"""
import json
import os
from pathlib import Path
import subprocess
import sys

root = Path(sys.argv[1])
root.mkdir(parents=True, exist_ok=True)

def run(args, cwd=None):
    return subprocess.check_output(args, cwd=cwd, text=True).strip()

def az(args):
    project_args = [] if args[:3] == ['repos', 'pr', 'update'] else ['--project', os.environ['AZURE_DEVOPS_TEST_PROJECT']]
    return json.loads(run(['az', *args, '--organization', os.environ['AZURE_DEVOPS_TEST_ORG'], *project_args, '-o', 'json']))

repo = next(r for r in az(['repos', 'list']) if r['name'] == 't3-factory-test')
branches = ['proof-43470-base', 'proof-43470-split', 'proof-43470-control']
if '--cleanup' in sys.argv:
    state = json.loads((root / 'seed.json').read_text())
    for pr in state['prs']:
        az(['repos', 'pr', 'update', '--id', str(pr['id']), '--status', 'abandoned'])
    refs = az(['repos', 'ref', 'list', '--repository', repo['id']])
    for ref in refs:
        if ref['name'] in ['refs/heads/' + b for b in branches]:
            az(['repos', 'ref', 'delete', '--repository', repo['id'], '--name', ref['name'],
                '--object-id', ref['objectId']])
    print('Synthetic PRs abandoned and fixture branches deleted.')
    sys.exit()

workspace = root / 'seed-repo'
workspace.mkdir()
run(['git', 'init', '--initial-branch=' + branches[0], str(workspace)])
(workspace / 'README.md').write_text('Reference rendering proof\n')
identity = ['-c', 'user.name=Scenario', '-c', 'user.email=scenario@example.invalid']
def commit(message):
    run(['git', 'add', '.'], workspace)
    run(['git', *identity, 'commit', '-m', message], workspace)

def push(branch):
    helper = '!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f'
    run(['git', '-c', 'credential.helper=' + helper, 'push', repo['remoteUrl'], branch], workspace)

commit('Initial synthetic sample')
push(branches[0])
prs = []
for kind in ['split', 'control']:
    branch = 'proof-43470-' + kind
    run(['git', 'checkout', '-b', branch], workspace)
    (workspace / 'sample.txt').write_text(kind + '\n')
    commit('Synthetic ' + kind)
    push(branch)
    body = ('Read [ref] and ![logo][img].\n\n'
            + ('https://example.com/shot.png\n\n' if kind == 'split' else '')
            + '[ref]: https://example.com/?x=1&amp;copy;\n'
            + '[img]: https://example.com/logo.png "a &amp;copy; &amp;#65;"')
    pr = az(['repos', 'pr', 'create', '--repository', repo['id'], '--source-branch', branch,
             '--target-branch', branches[0], '--title', 'Reference entities ' + kind + ' 43470',
             '--description', body])
    prs.append({'kind': kind, 'id': pr['pullRequestId'],
                'url': repo['webUrl'] + '/pullrequest/' + str(pr['pullRequestId'])})
    run(['git', 'checkout', branches[0]], workspace)
(root / 'seed.json').write_text(json.dumps({'remote': repo['remoteUrl'], 'prs': prs}))
print('Created split and control PRs:', [p['id'] for p in prs])
