"""Merge the INODE64 migration with the latest upstream migration of hc.api.

The INODE64 migration keeps the dependency it was written with, because it is
already applied on the servers. When upstream adds migrations after that one,
hc.api has two leaf nodes and `manage.py migrate` refuses to run. This writes
an empty merge migration named after the upstream leaf, so a merge that is
already applied never changes its dependencies in a later version. Run from
the source directory; nothing is written when there is a single leaf.
"""

import os
import sys

sys.path.insert(0, os.getcwd())
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hc.settings")

import django  # noqa: E402

django.setup()

from django.db.migrations.loader import MigrationLoader  # noqa: E402

OURS = "0125_check_notify_every_ping"

leaves = [name for _, name in MigrationLoader(None).graph.leaf_nodes("api")]
if OURS not in leaves:
    sys.exit(f"merge-migrations: {OURS} is not a leaf of hc.api: {leaves}")

upstream = [name for name in leaves if name != OURS]
if not upstream:
    sys.exit(0)
if len(upstream) > 1:
    sys.exit(f"merge-migrations: several upstream leaves in hc.api: {upstream}")

name = f"inode64_merge_{upstream[0]}"
path = os.path.join("hc", "api", "migrations", f"{name}.py")
with open(path, "w") as f:
    f.write(
        "# Generated by the www-apps/healthchecks ebuild (USE=inode64)\n\n"
        "from django.db import migrations\n\n\n"
        "class Migration(migrations.Migration):\n"
        f"    dependencies = [(\"api\", \"{upstream[0]}\"), (\"api\", \"{OURS}\")]\n\n"
        "    operations = []\n"
    )
print(f"merge-migrations: wrote {path}")
