#! /usr/bin/env python

import pathlib

import packaging.version
import yuio.app
import yuio.git
import yuio.io


@yuio.app.app
def main(
    version_str: str = yuio.app.positional(),
    dry_run: bool = False,
    push: bool = False,
):
    version = packaging.version.Version(
        version_str.removeprefix("refs/tags/").removeprefix("v")
    )

    if version.epoch:
        raise yuio.app.AppError("Epoch not supported")
    if version.is_prerelease:
        yuio.io.success("Nothing to do: version is a pre-release")
        return

    repo = yuio.git.Repo(pathlib.Path(__file__).parent)

    branches = []
    for components in [(version.major,), (version.major, version.minor)]:
        branch = "v" + ".".join(map(str, components))
        branches.append(branch)
        yuio.io.info(
            "Updating branch `%s` to current `HEAD`"
            + (" (dry-run)" if dry_run else ""),
            branch,
        )
        if not dry_run:
            repo.git("branch", "-f", branch, "HEAD")
            branch_status = repo.show(branch)
            if not branch_status:
                raise yuio.app.AppError("Failed to get status for branch `%s`", branch)
            else:
                yuio.io.success(
                    "Branch `%s` now points to `%s`", branch, branch_status.short_hash
                )

    if push:
        if dry_run:
            yuio.io.info("Skipping push: dry-run")
        else:
            yuio.io.info("Pushing branches: `%r`", branches)
            repo.git("push", "-f", "origin", *branches)

    yuio.io.success("Done")


if __name__ == "__main__":
    main.run()
