"""Create disposable GitLab data; requires authenticated glab and git. Prints fixture JSON."""
import datetime
import json
import os
import pathlib
import subprocess
import tempfile
import uuid


def api(*args):
    return json.loads(subprocess.check_output(["glab", "api", *args]))


project = api("projects", "-X", "POST", "-f", "name=Chronological activity proof",
              "-f", "path=t3-time-proof-" + uuid.uuid4().hex[:12],
              "-f", "visibility=private", "-f", "initialize_with_readme=true")
with tempfile.TemporaryDirectory(prefix="time-proof-") as root:
    repo = pathlib.Path(root) / "repo"
    subprocess.run(["git", "clone", "--quiet", project["http_url_to_repo"], str(repo)], check=True)
    def git(*args, **kwargs):
        return subprocess.run(["git", *args], cwd=repo, check=True, **kwargs)
    git("checkout", "-b", "offset-commit")
    (repo / "offset.txt").write_text("Synthetic chronological ordering evidence\n")
    git("add", ".")
    date = (datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=2)).astimezone(
        datetime.timezone(datetime.timedelta(hours=14))).isoformat()
    git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit",
        "-m", "Older commit (UTC+14)", env={**os.environ, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date})
    git("push", "--quiet", "origin", "offset-commit")
mr = api(f'projects/{project["id"]}/merge_requests', "-X", "POST", "-f", "source_branch=offset-commit",
         "-f", "target_branch=main", "-f", "title=Repro 28391 chronological activity")
api(f'projects/{project["id"]}/merge_requests/{mr["iid"]}/notes', "-X", "POST",
    "-f", "body=Newer comment (UTC, two hours later)")
print(json.dumps({"remote": project["http_url_to_repo"], "projectId": project["id"], "iid": mr["iid"]}))
# After verification, delete only the disposable project: glab api projects/<projectId> -X DELETE
