from pathlib import Path
from conan import ConanFile
from collections import OrderedDict
from conan.tools.files import copy


class ConanOpenVapiDevTools(ConanFile):
    name = "open-vehicle-api-dev-tools"
    license = "Apache-2.0"
    author = "thommyho <thommyho1988@gmail.com>"
    url = "https://github.com/eclipse-openvehicle-api/openvehicle-api"
    homepage = "https://eclipse.dev/openvehicle-api/"

    # "application" tells Conan this is a tool/app, confusingly implying it doesn't have headers/libs
    package_type = "application"

    description = (
        "The Eclipse Open Vehicle API (VAPI) provides runtime "
        "to run vehicle abstraction interfaces for signal- and event-driven functions."
    )
    topics = ("automotive", "sdv", "embedded", "c++", "tools")

    # We need settings to compile the tools initially (or download correct binary)
    settings = "os", "arch", "compiler", "build_type"

    exports_sources = "LICENSE"

    def build_requirements(self):
        # We need the full dev package to extract the tools from it
        self.tool_requires(f"open-vehicle-api-dev-full/{self.version}")

    def package_id(self):
        # Allow this package to be reused regardless of the consumer's compiler/build_type.
        # The tools are binaries; their compatibility depends on OS/Arch.
        del self.info.settings.compiler
        del self.info.settings.build_type

    def package(self):
        # Get the build environment from the 'open-vehicle-api-dev' requirement
        # Note: We must access the dependency using the exact name/version from build_requirements
        dep_name = f"open-vehicle-api-dev-full/{self.version}"

        # Safety check: ensure dependency exists
        if dep_name not in self.dependencies.build:
            # Fallback or error handling if needed, though Conan usually ensures this
            pass

        env = self.dependencies.build[dep_name].buildenv_info.vars(self)
        vars_map = OrderedDict(env)

        # SDV_FRAMEWORK_DEV_TOOLS should point to where the binaries are in the build requirement
        path_dev_tools_str = vars_map.get("SDV_FRAMEWORK_DEV_TOOLS")

        if path_dev_tools_str:
            path_dev_tools = Path(path_dev_tools_str)

            # Copy specific tools to our package's bin directory
            tools_to_copy = ["sdv_idl_compiler", "sdv_dbc_util", "sdv_vss_util", "sdv_packager", "core_services.sdv"]

            for tool in tools_to_copy:
                copy(
                    self,
                    tool,
                    src=path_dev_tools,
                    dst=Path(self.package_folder) / "bin",
                )
                # Handle Windows .exe extension if necessary
                copy(
                    self,
                    f"{tool}.exe",
                    src=path_dev_tools,
                    dst=Path(self.package_folder) / "bin",
                )

        # Copy License
        # Note: Adjust relative path as per your repo structure
        license_src = Path(self.recipe_folder) / ".." / "es"
        if license_src.exists():
            copy(self, "LICENSE*", src=license_src, dst=self.package_folder)

    def package_info(self):
        self.cpp_info.bindirs = ["bin"]

        # Define environment variable so consumers can find the tools
        pkg_path = Path(self.package_folder)
        tools_bin_path = (pkg_path / "bin").as_posix()

        self.runenv_info.define_path("SDV_FRAMEWORK_RUNTIME", tools_bin_path)
        self.buildenv_info.define_path("SDV_FRAMEWORK_RUNTIME", tools_bin_path)

        self.runenv_info.define_path("SDV_FRAMEWORK_DEV_TOOLS", tools_bin_path)
        self.buildenv_info.define_path("SDV_FRAMEWORK_DEV_TOOLS", tools_bin_path)
