"""Create the real GitLab MR used by the rendering proof; requires glab login."""
import json
import subprocess
import sys


def api(method, path, payload=None):
    command = ["glab", "api", "-X", method, path]
    if payload is not None:
        command += ["--input", "-"]
    result = subprocess.run(command, input=json.dumps(payload) if payload else None,
                            capture_output=True, text=True, check=True)
    return json.loads(result.stdout) if result.stdout.strip() else None


name = sys.argv[1] if len(sys.argv) > 1 else "proof-48860-20261204"
project = api("POST", "projects", {"name": name, "visibility": "private", "initialize_with_readme": True})
path = f"projects/{project['id']}"
api("POST", path + "/repository/branches", {"branch": "example", "ref": "main"})
api("POST", path + "/repository/commits", {
    "branch": "example", "commit_message": "Add example",
    "actions": [{"action": "create", "file_path": "example.txt", "content": "Example"}],
})
body = 'Example <span title="`">syntax</span>: `fetch\nhttps://example.com/release-demo.mp4\n--output clip`\n\nEnd of description.'
mr = api("POST", path + "/merge_requests", {
    "source_branch": "example", "target_branch": "main",
    "title": "Inline command rendering", "description": body,
})
confirmed = api("GET", path + f"/merge_requests/{mr['iid']}")
assert confirmed["description"] == body
print(json.dumps({"projectId": project["id"], "repository": project["path_with_namespace"],
                  "number": mr["iid"], "description": confirmed["description"]}, indent=2))
# After the proof, schedule this scratch project for deletion:
# glab api -X DELETE projects/<projectId>
