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

from catalog_update.upgrade_strategy import semantic_versioning


RE_STABLE_VERSION_BASE = r'\d+\.\d+\.\d+'
ENUMS = {
    'image': {
        'RE_STABLE_VERSION': re.compile(rf'v{RE_STABLE_VERSION_BASE}'),
        'STRIP_TEXT': 'v'
    },
    'mlImage': {
        'RE_STABLE_VERSION': re.compile(rf'v{RE_STABLE_VERSION_BASE}'),
        'STRIP_TEXT': 'v'
    },
    'mlCudaImage': {
        'RE_STABLE_VERSION': re.compile(rf'v{RE_STABLE_VERSION_BASE}-cuda'),
        'STRIP_TEXT': 'v'
    },
    'mlOpenvinoImage': {
        'RE_STABLE_VERSION': re.compile(rf'v{RE_STABLE_VERSION_BASE}-openvino'),
        'STRIP_TEXT': 'v'
    },
    'pgvectorImage': {
        'RE_STABLE_VERSION': re.compile(rf'pg15-v{RE_STABLE_VERSION_BASE}'),
        'STRIP_TEXT': 'pg15-v'
    }
}


def strip_text(key, STRIP_TEXT):
    key = key.replace('-cuda', '').replace('-openvino', '')
    return key.strip(STRIP_TEXT)


def newer_mapping(image_tags):

    output = {
        "tags": {},
        "app_version": ""
    }

    for key in image_tags.keys():
        STRIP_TEXT = ENUMS[key].get('STRIP_TEXT', None)
        RE_STABLE_VERSION = ENUMS[key].get('RE_STABLE_VERSION')

        if (STRIP_TEXT is None) or (RE_STABLE_VERSION is None):
            continue

        tags = {strip_text(t, STRIP_TEXT): t for t in image_tags[key] if RE_STABLE_VERSION.fullmatch(t)}
        version = semantic_versioning(list(tags))

        if not version:
            continue

        if key == 'image':
            output['app_version'] = version

        output['tags'][key] = tags[version]

    return output


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

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