#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright © Huawei Technologies Co., Ltd. 2022-2025. All rights reserved.
import os
import stat
import re
import time

import yaml
from conan import ConanFile
from conan.tools.files import copy, update_conandata
from conan.tools.scm import Git

required_conan_version = ">=2.13.0"


class OpenUBMCSdkConan(ConanFile):
    name = "openubmc_sdk"
    url = "https://www.openubmc.cn"
    requires = []
    license = "Mulan PSL v2"
    options = {}
    _subsys_com_list = {}
    settings = None

    def layout(self):
        self.folders.build = "build/sdk"
        self.folders.generators = os.path.join(self.folders.build, "generators")

    def source(self):
        git = Git(self)
        sources = self.conan_data["sources"][self.version]
        if sources["url"] and sources["commit"]:
            git.fetch_commit(url=sources["url"], commit=sources["commit"])
        else:
            copy(self, "*", src=sources["pwd"], dst=".")

    def export(self):
        git = Git(self, self.recipe_folder)
        if git.is_dirty():
            update_conandata(self, {"sources": {self.version: {"commit": None, "url": None, "pwd": os.path.dirname(os.path.dirname(os.getcwd())), "timestamp": int(time.time())}}})
            return
        url = None
        commit = git.get_commit(repository=True)
        remotes = git.run("remote")
        for remote in remotes.splitlines():
            try:
                ret = git.run(f"ls-remote {remote} | grep {commit}")
                if ret:
                    url = git.get_remote_url(remote)
                    break
            except Exception as e:
                url = None
        if not url:
            update_conandata(self, {"sources": {self.version: {"commit": None, "url": None, "pwd": os.path.dirname(os.path.dirname(os.getcwd())), "timestamp": int(time.time())}}})
            return
        update_conandata(self, {"sources": {self.version: {"commit": commit, "url": url}}})

    def build(self):
        path = "../subsys"
        real_path = os.path.realpath(path)
        for file_name in os.listdir(real_path):
            with open(os.path.join(real_path, file_name)) as fp:
                packages = yaml.safe_load(fp).get("dependencies")
            for item in packages:
                package = item["conan"]
                comp_name = package.split("/")[0]
                self._subsys_com_list[comp_name] = package
        build_path = os.path.join(os.getcwd())
        self._overrite_manifest(build_path)

    def package(self):
        copy(self, "manifest.yml", src=self.build_folder, dst=self.package_folder)
        copy(self, "openubmc_sdk.lock", src=self.build_folder, dst=self.package_folder)

    def _overrite_manifest(self, file_dir):
        config_path = os.path.join(file_dir, "manifest.yml")
        with open(config_path, "r") as yaml_fp:
            obj = yaml.safe_load(yaml_fp)
        self.version = obj["base"]["version"]
        deps = []
        conan_list = obj.get("dependencies")
        for conan in conan_list:
            version_split = re.split(r"[/, @]", conan["conan"])
            pkg_name = version_split[0]
            if pkg_name in self._subsys_com_list:
                conan["conan"] = self._subsys_com_list[pkg_name]
            deps.append(conan)
        obj["dependencies"] = deps
        if obj.get("base"):
            del obj["base"]
        with os.fdopen(
            os.open(
                config_path,
                os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
                stat.S_IWUSR | stat.S_IRUSR,
            ),
            "w+",
        ) as file_handler:
            file_handler.write(
                f"# yaml-language-server: $schema=/usr/share/bmcgo/schema/manifest.platform.schema.json\n"
            )
            file_handler.write(yaml.safe_dump(obj))
