#!/usr/bin/python3
import json
import sys
import re

from catalog_update.upgrade_strategy import semantic_versioning
from catalog_validation.exceptions import ValidationException

version_regx = r'[\w]*-v[0-9]+.[0-9]+.[0-9]+-go[0-9]+.[0-9].+[0-9]+'
version_with_arch = version_regx + r'[-\w]*'
sub_go_version = r'-go[0-9]+.[0-9].+[0-9]+[-\w]*'
version_hash = r'[\w]*-v'
app_version_regx = 'v[0-9]+.[0-9]+.[0-9]'


def newer_mapping(image_tags):
    key = list(image_tags.keys())[0]
    tags = {}
    for tag in image_tags[key]:
        match = re.fullmatch(version_with_arch, tag)
        if match:
            removed_go_arch_version = re.sub(sub_go_version, '', tag)
            app_version = re.sub(version_hash, '', removed_go_arch_version)
            if tags.get(app_version):
                tags.get(app_version).append(tag)
            else:
                tags[app_version] = [tag]
    version = semantic_versioning(list(tags))
    if not version:
        return {}

    version_tag = tags[version][0]
    for tag in tags.get(version):
        archi = re.sub(version_regx, '', tag)
        if archi == 'amd64' or archi == '':
            version_tag = tag
            break
    app_version = re.findall(app_version_regx, version_tag).pop()
    return {
        'tags': {key: f'{version_tag}'},
        'app_version': f'{app_version}',
    }


if __name__ == '__main__':
    try:
        versions_json = json.loads(sys.stdin.read())
    except ValueError:
        raise ValidationException('Invalid JSON')

    print(json.dumps(newer_mapping(versions_json)))
