"""Create the synthetic Azure PR fixture. Requires AZURE_DEVOPS_TEST_ORG,
AZURE_DEVOPS_TEST_PROJECT and AZURE_DEVOPS_EXT_PAT in the environment.
Run in a new scratch directory; abandon the PR and delete the repository afterwards.
Set PROOF_AZURE_REMOTE to the printed remote before running the scenario.
"""
import json
import os
from pathlib import Path
import subprocess
import uuid

name = "deleted-files-proof-" + uuid.uuid4().hex[:8]
org = os.environ["AZURE_DEVOPS_TEST_ORG"]
project = os.environ["AZURE_DEVOPS_TEST_PROJECT"]

def az(*args):
    return json.loads(subprocess.check_output([
        "az", *args, "--organization", org, "--project", project, "-o", "json"
    ], text=True))

repo = az("repos", "create", "--name", name)
workspace = Path(name)
workspace.mkdir()

def git(*args):
    return subprocess.check_output(["git", *args], cwd=workspace, text=True)

git("init", "-b", "main")
git("config", "user.name", "Scenario")
git("config", "user.email", "scenario@example.invalid")
for filename, contents in {
    "edited.txt": "original line\nunchanged line\n",
    "before.txt": "renamed content\n",
    "gone.txt": "deleted line one\ndeleted line two\n",
}.items():
    (workspace / filename).write_text(contents)
git("add", ".")
git("commit", "-m", "Initial files")
git("remote", "add", "origin", repo["remoteUrl"])
git("checkout", "-b", "feature")
(workspace / "added.txt").write_text("added content\n")
(workspace / "edited.txt").write_text("edited line\nunchanged line\n")
git("mv", "before.txt", "after.txt")
git("rm", "gone.txt")
git("add", ".")
git("commit", "-m", "Add edit rename delete")
print(git("diff", "--name-status", "-M", "main", "feature"))
git("-c", 'credential.helper=!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f',
    "push", "origin", "main", "feature")
pr = az("repos", "pr", "create", "--repository", repo["id"], "--source-branch", "feature",
        "--target-branch", "main", "--title", "Deleted file proof", "--draft", "true")
print(json.dumps({"remote": repo["remoteUrl"], "repositoryId": repo["id"], "pullRequestId": pr["pullRequestId"]}))
