#!/usr/bin/env python3
from __future__ import annotations

import os
import sys
from os.path import dirname, join, realpath

import yaml

PREFIX = "Product Area: "
LABELS_YAML = ".github/labels.yml"


def main():
    # Run from project root.
    os.chdir(realpath(join(dirname(sys.argv[0]), "..")))

    product_owners = yaml.safe_load(open(sys.argv[1]))
    labels = open(LABELS_YAML)
    areas = [
        # For `sentry` repo we don't want SDK or Docs areas, that stuff should
        # be transferred to other repos.
        x
        for x in product_owners["by_area"]
        if not x.startswith("SDK") and not x == "Docs"
    ]

    fastforward = False
    head: list[str] = []
    area_lines = ["- name: 'Product Area: Unknown'\n", "  color: '8D5494'\n"]
    tail: list[str] = []
    current = head

    # Best to look the other way, Buck. This is just waaaay easier than trying to
    # use ruamel.yaml to preserve comments and other formatting. What this does is
    # loop through line by line, collecting everything before the Product Area
    # labels in `head` and everything after in `tail`. It "fast-forwards" past the
    # existing Product Area labels. Then we generate output for the new Product
    # Area labels, then emit the three parts (head, area_lines, tail) in order.

    for line in labels:
        if line == "\n":
            fastforward = False
        elif fastforward:
            continue
        elif line.startswith("- name: 'Product Area: "):
            fastforward = True
            current = tail
            continue
        current.append(line)

    for area in areas:
        # These are specifically placed at the front and end of the list of product areas.
        # They will always exist, so ignore what is coming in from security-as-code as a workaround.
        if area != "Other" and area != "Unknown":
            if "'" in area:
                area_lines.append(f'- name: "Product Area: {area}"\n')
            else:
                area_lines.append(f"- name: 'Product Area: {area}'\n")
            area_lines.append("  color: '8D5494'\n")

    area_lines += ["- name: 'Product Area: Other'\n", "  color: '8D5494'\n"]

    with open(".github/labels.yml", "w+") as fp:
        fp.writelines(head)
        fp.writelines(area_lines)
        fp.writelines(tail)

    # Now for issue templates. Same game. Hang in there.

    BEGINNING = "        # begin product areas - autogenerated by bin/react-to-product-owners-yml-changes.py\n"
    END = "        # end product areas\n"

    for template in ("bug", "feature", "support"):
        filepath = f".github/ISSUE_TEMPLATE/{template}.yml"
        head = []
        area_lines = [BEGINNING, "        - 'Unknown'\n"]
        tail = []
        current = head
        for line in open(filepath):
            if line == END:
                fastforward = False
            elif line == BEGINNING:
                fastforward = True
                current = tail
            elif not fastforward:
                current.append(line)

        for area in areas:
            if area != "Other" and area != "Unknown":
                if "'" in area:
                    area_lines.append(f'        - "{area}"\n')
                else:
                    area_lines.append(f"        - '{area}'\n")

        area_lines += ["        - 'Other'\n", END]

        with open(filepath, "w+") as fp:
            fp.writelines(head)
            fp.writelines(area_lines)
            fp.writelines(tail)

    return 0


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