#!/usr/bin/env python3

import fileinput
import os.path
import sys
from os import getenv

from lib import get_gh_repo, re_ga
from lib.uiutil import run, run_txtcapture

def main() -> int:
    chart_version = getenv("CHART_VERSION")
    if not (chart_version and chart_version.startswith("v") and re_ga.match(chart_version[1:])):
        sys.stderr.write(f'Usage: CHART_VERSION=v7.Y.Z {os.path.basename(sys.argv[0])}\n')
        return 2

    content_gittag = f"chart/{chart_version}"

    content_title = f"Emissary Ingress Chart {chart_version[1:]}"

    content_body = f"""
## :tada: Emissary Ingress Chart {chart_version[1:]} :tada:

Upgrade Emissary - https://www.getambassador.io/reference/upgrading#helm.html
View changelog - https://github.com/emissary-ingress/emissary/blob/master/charts/emissary-ingress/CHANGELOG.md

---
"""
    in_changelog = False
    for line in fileinput.FileInput("charts/emissary-ingress/CHANGELOG.md"):
        if in_changelog:
            if line.startswith("## v"):
                break
            content_body += line
        if line == f"## {chart_version}\n":
            in_changelog = True
    content_body = content_body.strip()

    run([
        "gh", "release", "create",
        "--repo="+get_gh_repo(),
        "--title="+content_title,
        "--notes="+content_body,
        content_gittag])

    url = run_txtcapture([
        "gh", "release", "view",
        "--json=url",
        "--jq=.url",
        "--repo="+get_gh_repo(),
        content_gittag])
    print(f'echo "url={url}" >> $GITHUB_OUTPUT')


if __name__ == '__main__':
    sys.exit(main())