from __future__ import annotations

import datetime as dt
import subprocess
from pathlib import Path


def get_timestamp_tag(today: dt.date) -> str:
    year_suffix = today.year % 100
    day_of_year = today.timetuple().tm_yday
    return f"{year_suffix}.{day_of_year}"


def run_command(command: list[str], repo_root: Path) -> int:
    print(" ".join(command))
    result = subprocess.run(command, cwd=str(repo_root))
    return result.returncode


def main() -> int:
    repo_root = Path(__file__).resolve().parents[1]

    today = dt.date.today()
    timestamp_tag = get_timestamp_tag(today)

    local_image = "troogs/astrain"
    registry_image = "git.beging.de/troogs/astrain"
    tags = ["latest", timestamp_tag]

    for tag in tags:
        tag_cmd = [
            "docker",
            "tag",
            f"{local_image}:{tag}",
            f"{registry_image}:{tag}",
        ]
        print(f"Tagging {local_image}:{tag} as {registry_image}:{tag}")
        exit_code = run_command(tag_cmd, repo_root)
        if exit_code != 0:
            return exit_code

    for tag in tags:
        push_cmd = [
            "docker",
            "push",
            f"{registry_image}:{tag}",
        ]
        print(f"Pushing {registry_image}:{tag}")
        exit_code = run_command(push_cmd, repo_root)
        if exit_code != 0:
            return exit_code

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
