# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

import re

from openvino import get_version as get_ie_version  # pylint: disable=no-name-in-module,import-error


def extract_release_version(version: str):
    patterns = [
        # captures release version set by CI for example: '2021.1.0-1028-55e4d5673a8'
        r"^([0-9]+).([0-9]+)*",
        # captures release version generated by MO from release branch, for example: 'custom_releases/2021/1_55e4d567'
        r"_releases/([0-9]+)/([0-9]+)_*"
    ]

    for pattern in patterns:
        m = re.search(pattern, version)
        if m and len(m.groups()) == 2:
            return m.group(1), m.group(2)
    return None, None


def simplify_version(version: str):
    release_version = extract_release_version(version)
    if release_version == (None, None):
        return "custom"
    return "{}.{}".format(*release_version)


def get_simplified_ie_version(version=None):
    from openvino import get_version  # pylint: disable=no-name-in-module,import-error
    if version is None:
        version = get_version()

    # To support legacy OV versions
    m = re.match(r"^([0-9]+).([0-9]+).(.*)", version)
    if m and len(m.groups()) == 3:
        return simplify_version(m.group(3))
    return simplify_version(version)


def extract_hash_from_version(full_version: str):
    res = re.findall(r'[-_]([a-f0-9]{7,40})', full_version)
    if len(res) > 0:
        return res[0]
    else:
        return None


class SingletonMetaClass(type):
    def __init__(self, cls_name, super_classes, dic):
        self.__single_instance = None
        super().__init__(cls_name, super_classes, dic)

    def __call__(cls, *args, **kwargs):
        if cls.__single_instance is None:
            cls.__single_instance = super(SingletonMetaClass, cls).__call__(*args, **kwargs)
        return cls.__single_instance


class VersionChecker(metaclass=SingletonMetaClass):
    def __init__(self):
        self.runtime_checked = False
        self.mo_version = None
        self.ie_version = None
        self.mo_simplified_version = None
        self.ie_simplified_version = None

    def get_ie_version(self):
        if self.ie_version:
            return self.ie_version
        self.ie_version = get_ie_version()
        return self.ie_version

    def get_ie_simplified_version(self):
        if self.ie_simplified_version:
            return self.ie_simplified_version
        self.ie_simplified_version = get_simplified_ie_version()
        return self.ie_simplified_version
