/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * 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 "cuttlefish/host/commands/cvd/cli/request_context.h"

#include <memory>
#include <string>
#include <vector>

#include <fmt/ranges.h>  // NOLINT(misc-include-cleaner): version difference

#include "cuttlefish/common/libs/utils/contains.h"
#include "cuttlefish/host/commands/cvd/cli/command_request.h"
#include "cuttlefish/host/commands/cvd/cli/commands/bugreport.h"
#include "cuttlefish/host/commands/cvd/cli/commands/cache.h"
#include "cuttlefish/host/commands/cvd/cli/commands/clear.h"
#include "cuttlefish/host/commands/cvd/cli/commands/command_handler.h"
#include "cuttlefish/host/commands/cvd/cli/commands/create.h"
#include "cuttlefish/host/commands/cvd/cli/commands/display.h"
#include "cuttlefish/host/commands/cvd/cli/commands/env.h"
#include "cuttlefish/host/commands/cvd/cli/commands/fetch.h"
#include "cuttlefish/host/commands/cvd/cli/commands/fleet.h"
#include "cuttlefish/host/commands/cvd/cli/commands/help.h"
#include "cuttlefish/host/commands/cvd/cli/commands/lint.h"
#include "cuttlefish/host/commands/cvd/cli/commands/load_configs.h"
#include "cuttlefish/host/commands/cvd/cli/commands/login.h"
#include "cuttlefish/host/commands/cvd/cli/commands/logs.h"
#include "cuttlefish/host/commands/cvd/cli/commands/monitor/command_handler.h"
#include "cuttlefish/host/commands/cvd/cli/commands/power_btn.h"
#include "cuttlefish/host/commands/cvd/cli/commands/powerwash.h"
#include "cuttlefish/host/commands/cvd/cli/commands/remove.h"
#include "cuttlefish/host/commands/cvd/cli/commands/reset.h"
#include "cuttlefish/host/commands/cvd/cli/commands/restart.h"
#include "cuttlefish/host/commands/cvd/cli/commands/screen_recording.h"
#include "cuttlefish/host/commands/cvd/cli/commands/setup.h"
#include "cuttlefish/host/commands/cvd/cli/commands/snapshot.h"
#include "cuttlefish/host/commands/cvd/cli/commands/start.h"
#include "cuttlefish/host/commands/cvd/cli/commands/status.h"
#include "cuttlefish/host/commands/cvd/cli/commands/stop.h"
#include "cuttlefish/host/commands/cvd/cli/commands/version.h"
#include "cuttlefish/host/commands/cvd/instances/instance_manager.h"
#include "cuttlefish/host/commands/cvd/instances/lock/instance_lock.h"
#include "cuttlefish/result/result.h"

namespace cuttlefish {

namespace {

bool CanHandle(const CvdCommandHandler& handler, const CommandRequest& request) {
  return Contains(handler.CmdList(), request.Subcommand());
}

std::vector<std::string> GetPossibleCommands(
    const CommandRequest& request,
    const std::vector<std::unique_ptr<CvdCommandHandler>>& handlers) {
  std::vector<std::string> possibilities;
  if (request.Subcommand().empty()) {
    return possibilities;
  }

  for (auto& handler : handlers) {
    for (const std::string& command : handler->CmdList()) {
      if (!command.empty() && command.front() == request.Subcommand().front()) {
        possibilities.push_back(command);
        break;
      }
    }
  }
  return possibilities;
}

}  //  namespace

RequestContext::RequestContext(InstanceManager& instance_manager,
                               InstanceLockFileManager& lock_file_manager) {
  request_handlers_.emplace_back(NewCvdCacheCommandHandler());

  request_handlers_.emplace_back(NewCvdCreateCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewCvdDisplayCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewCvdEnvCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewCvdFetchCommandHandler());
  request_handlers_.emplace_back(NewCvdFleetCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewCvdClearCommandHandler(instance_manager));
  request_handlers_.emplace_back(
      NewCvdBugreportCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewCvdStopCommandHandler(instance_manager));
  request_handlers_.emplace_back(
      NewCvdHelpHandler(this->request_handlers_));
  request_handlers_.emplace_back(NewLintCommand());
  request_handlers_.emplace_back(NewLoadConfigsCommand(instance_manager));
  request_handlers_.emplace_back(NewLoginCommand());
  request_handlers_.emplace_back(
      NewCvdDevicePowerBtnCommandHandler(instance_manager));
  request_handlers_.emplace_back(
      NewCvdDevicePowerwashCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewCvdMonitorCommandHandler(instance_manager));
  request_handlers_.emplace_back(
      NewCvdDeviceRestartCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewRemoveCvdCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewCvdResetCommandHandler(instance_manager));
  request_handlers_.emplace_back(
      NewScreenRecordingCommandHandler(instance_manager));
  request_handlers_.emplace_back(
      NewCvdSnapshotCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewCvdSetupHandler());
  request_handlers_.emplace_back(NewCvdStartCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewCvdStatusCommandHandler(instance_manager));
  request_handlers_.emplace_back(NewCvdVersionHandler());
  request_handlers_.emplace_back(NewCvdLogsHandler(instance_manager));
}

Result<CvdCommandHandler*> RequestContext::Handler(
    const CommandRequest& request) {
  return CF_EXPECT(RequestHandler(request, request_handlers_));
}

Result<CvdCommandHandler*> RequestHandler(
    const CommandRequest& request,
    const std::vector<std::unique_ptr<CvdCommandHandler>>& handlers) {
  std::vector<CvdCommandHandler*> compatible_handlers;
  for (auto& handler : handlers) {
    if (CanHandle(*handler, request)) {
      compatible_handlers.push_back(handler.get());
    }
  }

  CF_EXPECT(compatible_handlers.size() < 2,
            "The command matched multiple handlers which should not happen.  "
            "Please open a bug with the cvd/Cuttlefish team and include the "
            "exact command that raised the error so it can be fixed.");

  if (compatible_handlers.size() != 1) {
    const std::vector<std::string> possible_commands =
        GetPossibleCommands(request, handlers);
    std::string addendum;
    if (!possible_commands.empty()) {
      addendum = fmt::format("\n\nDid you mean one of:\n\t{}",
                             fmt::join(possible_commands, "\n\t"));
    }
    return CF_ERRF(
        "Unable to find a matching command for \"cvd {}\".\nMaybe there "
        "is a typo?  Run `cvd help` for a list of commands.{}",
        request.Subcommand(), addendum);
  }
  return compatible_handlers[0];
}

}  // namespace cuttlefish
