import os
from pathlib import Path

import tortoise.cli.cli as tortoise_cli
from tortoise.migrations.writer import MigrationWriter


def _install_hook():
    original_write = MigrationWriter.write

    def write_and_record(self, *args, **kwargs):
        path = original_write(self, *args, **kwargs)
        Path("latest_migration.manifest").write_text(f"{self.name}\n", encoding="utf-8")
        return path

    MigrationWriter.write = write_and_record


def main():
    # it's possible to opt-out
    enabled = os.environ.get("BAKIT_TORTOISE_HOOK", "1") != "0"
    if enabled:
        _install_hook()

    tortoise_cli.main()
