#!/usr/bin/env python3

import argparse
import sys

from redminelib import Redmine
from ruamel.yaml import YAML

REDMINE_URL = 'https://projects.theforeman.org'

def find_redmine_versions(project_id: str, prefix: str) -> dict[str, int]:
    """
    Find all X.Y.Z versions in Redmine based on version X.Y
    """
    redmine = Redmine(REDMINE_URL)
    versions = redmine.version.filter(project_id=project_id)

    return {v.name: v.id for v in versions if v.name.startswith(prefix)}

def create_mash_config(version: str, gpg_key: str, redmine_project: str) -> None:
    """
    Create a mash config based on the nightly config
    """
    yaml = YAML()
    yaml.default_flow_style = False
    yaml.indent(mapping=2, sequence=4, offset=2)
    yaml.explicit_start = True

    data = yaml.load(sys.stdin.read().replace('-nightly', f'-{version}'))

    data[':nightly'] = False
    data[':strict_keys'] = True
    data[':gpg_key'] = gpg_key
    data[':repos'] = []

    data[':releases'] = {}
    for version_name, version_id in find_redmine_versions(redmine_project, f'{version}.').items():
        data[':releases'][f':{version_name}'] = {':redmine_version_id': version_id}

    for tag in data[':tags']:
        tag['based_off'] = tag['name'].replace(version, 'nightly')

        try:
            group_source_tag = tag['build_package_group_source_tag'].replace(version, 'nightly')
        except KeyError:
            pass
        else:
            tag['build_package_group_source_tag'] = group_source_tag

    yaml.dump(data, sys.stdout)

def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument('version', help='Version as X.Y')
    parser.add_argument('gpg_key', help='GPG key as the short 8 character key')
    parser.add_argument('redmine_project', help='Slug for the Redmine project')

    args = parser.parse_args()

    create_mash_config(args.version, args.gpg_key, args.redmine_project)

if __name__ == '__main__':
    main()
