# Copyright 2021 Ant Group Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import shutil
import subprocess
import sys
from pathlib import Path


def _build_lib(libname: str, force: bool = False) -> Path:
    target = f"//kcal:{libname}"
    dst_path = Path(f"kcal/{libname}.so")

    if dst_path.exists():
        if force:
            dst_path.unlink()
        else:
            print(f"{dst_path} exists, ignore build")
            return dst_path

    ver_info = sys.version_info
    version = f"{ver_info.major}.{ver_info.minor}"

    # Use -c opt by default to match manual builds
    # Can be overridden via KCAL_BUILD_MODE environment variable (opt/dbg/fastbuild)
    build_mode = os.getenv("KCAL_BUILD_MODE", "opt")

    args = [
        "bazelisk",
        "build",
        target,
        "-c",
        build_mode,
        f"--@rules_python//python/config_settings:python_version={version}",
    ]

    subprocess.run(args, check=True)
    dst_path.parent.mkdir(exist_ok=True)
    bzl_path = Path(f"bazel-bin/kcal/{libname}.so")
    shutil.copy2(bzl_path, dst_path)
    return dst_path


def build_libs():
    # pdm script command, please see the config([tool.pdm.scripts]) in pyproject.toml.
    force = os.getenv("KCAL_BUILD_FORCE", "false") == "true"
    _build_lib("libkcal", force)


def pdm_build_initialize(context):
    # pdm hook function, please refer to https://backend.pdm-project.org/hooks/
    # pdm build-config-settings: https://backend.pdm-project.org/build_config/#build-config-settings
    from packaging.tags import sys_tags, platform_tags

    context.config_settings["--plat-name"] = next(platform_tags())
    context.config_settings["--python-tag"] = next(sys_tags()).interpreter


def pdm_build_update_files(context, files: dict):
    force = os.getenv("KCAL_BUILD_FORCE", "false") == "true"
    libkcal = _build_lib("libkcal", force)
    files[str(libkcal)] = libkcal