// Copyright 2026 The OpenXLA Authors. All Rights Reserved.
//
// 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 "xprof/convert/unified_profile_processor_factory.h"

#include <memory>
#include <utility>

#include "absl/base/no_destructor.h"
#include "absl/functional/any_invocable.h"
#include "absl/log/log.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "absl/flags/flag.h"
#include "absl/synchronization/mutex.h"
#include "xprof/convert/tool_options.h"
#include "xprof/convert/unified_profile_processor.h"

ABSL_FLAG(bool, enable_unified_xprof, false, "Enable unified Xprof workflow");

namespace xprof {

UnifiedProfileProcessorFactory& UnifiedProfileProcessorFactory::GetInstance() {
  static absl::NoDestructor<UnifiedProfileProcessorFactory> instance;
  return *instance;
}

void UnifiedProfileProcessorFactory::Register(absl::string_view tool_name,
                                              Creator creator) {
  absl::MutexLock lock(mu_);
  if (creators_.contains(tool_name)) {
    LOG(WARNING) << "UnifiedProfileProcessor for tool: " << tool_name
                 << " is already registered and will be overwritten.";
  }
  creators_[tool_name] = std::move(creator);
}

std::unique_ptr<UnifiedProfileProcessor>
UnifiedProfileProcessorFactory::Create(
    absl::string_view tool_name,
    const tensorflow::profiler::ToolOptions& options) const {
  absl::string_view clean_tool_name = tool_name;
  if (absl::EndsWith(clean_tool_name, ".json")) {
    clean_tool_name.remove_suffix(5);
  } else if (absl::EndsWith(clean_tool_name, ".pb")) {
    clean_tool_name.remove_suffix(3);
  } else if (absl::EndsWith(clean_tool_name, ".pbtxt")) {
    clean_tool_name.remove_suffix(6);
  }

  absl::MutexLock lock(mu_);
  auto it = creators_.find(clean_tool_name);
  if (it == creators_.end()) {
    LOG(ERROR) << "No UnifiedProfileProcessor registered for tool: "
               << tool_name;
    return nullptr;
  }
  return it->second(options);
}

RegisterUnifiedProfileProcessor::RegisterUnifiedProfileProcessor(
    absl::string_view tool_name,
    UnifiedProfileProcessorFactory::Creator creator) {
  UnifiedProfileProcessorFactory::GetInstance().Register(tool_name,
                                                         std::move(creator));
}

}  // namespace xprof
