// Copyright 2024 Huawei Cloud Computing Technology 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.

#include "src/buildtool/common/location.hpp"

#include "fmt/core.h"
#include "src/buildtool/file_system/file_system_manager.hpp"
#include "src/buildtool/logging/log_level.hpp"
#include "src/buildtool/logging/logger.hpp"

auto ReadLocationObject(nlohmann::json const& location,
                        std::optional<std::filesystem::path> const& ws_root)
    -> expected<std::optional<location_res_t>, std::string> {
    if (not location.contains("path") or not location.contains("root")) {
        return unexpected(
            fmt::format("Malformed location object: {}", location.dump(-1)));
    }
    auto root = location["root"].get<std::string>();
    auto path = location["path"].get<std::string>();
    auto base = location.contains("base") ? location["base"].get<std::string>()
                                          : std::string(".");

    std::filesystem::path root_path{};
    if (root == "workspace") {
        if (not ws_root) {
            Logger::Log(LogLevel::Warning,
                        "Not in workspace root, ignoring location {}.",
                        location.dump(-1));
            return std::optional<location_res_t>{std::nullopt};
        }
        root_path = *ws_root;
    }
    if (root == "home") {
        root_path = FileSystemManager::GetUserHome();
    }
    if (root == "system") {
        root_path = FileSystemManager::GetCurrentDirectory().root_path();
    }
    return std::optional<location_res_t>{
        std::make_pair(std::filesystem::weakly_canonical(
                           std::filesystem::absolute(root_path / path)),
                       std::filesystem::weakly_canonical(
                           std::filesystem::absolute(root_path / base)))};
}
