#include "config.h"

#include <functional>
#include <cstdio>
#include <string>
#include <vector>
#include <torrent/rate.h>
#include <torrent/hash_string.h>
#include <torrent/utils/log.h>
#include <torrent/utils/directory_events.h>
#include <torrent/utils/file_stat.h>
#include <torrent/utils/string_manip.h>

#include "globals.h"
#include "control.h"
#include "command_helpers.h"
#include "core/download.h"
#include "core/download_list.h"
#include "core/manager.h"
#include "core/view_manager.h"
#include "rpc/command_scheduler.h"
#include "rpc/parse.h"
#include "rpc/parse_commands.h"
#include "utils/watch_ready_queue.h"

torrent::Object
apply_on_ratio(const torrent::Object& rawArgs) {
  auto& group_name = rawArgs.as_string();
  auto  view_itr = control->view_manager()->find(rpc::commands.call("group." + group_name + ".view", rpc::make_target()).as_string());

  if (view_itr == control->view_manager()->end())
    throw torrent::input_error("Could not find view.");

  // first argument:  minimum ratio to reach
  // second argument: minimum upload amount to reach [optional]
  // third argument:  maximum ratio to reach [optional]
  int64_t min_ratio  = rpc::commands.call("group." + group_name + ".ratio.min", rpc::make_target()).as_value();
  int64_t max_ratio  = rpc::commands.call("group." + group_name + ".ratio.max", rpc::make_target()).as_value();
  int64_t min_upload = rpc::commands.call("group." + group_name + ".ratio.upload", rpc::make_target()).as_value();

  std::vector<core::Download*> downloads;

  for  (auto itr = (*view_itr)->begin_visible(), last = (*view_itr)->end_visible(); itr != last; itr++) {
    if (!(*itr)->is_seeding() || rpc::call_command_value("d.ignore_commands", rpc::make_target(*itr)) != 0)
      continue;

    int64_t total_done   = (*itr)->download()->bytes_done();
    int64_t total_upload = (*itr)->info()->up_rate()->total();

    if (!(total_upload >= min_upload && total_upload * 100 >= total_done * min_ratio) &&
        !(max_ratio > 0 && total_upload * 100 > total_done * max_ratio))
      continue;

    downloads.push_back(itr->get());
  }

  auto ratio_command = "group." + group_name + ".ratio.command";

  for (const auto& download : downloads)
    rpc::commands.call_catch(ratio_command, rpc::make_target(download), torrent::Object(), "Ratio reached, but command failed: ");

  return torrent::Object();
}

torrent::Object
apply_start_tied() {
  for (const auto& download : *control->core()->download_list()) {
    if (rpc::call_command_value("d.state", rpc::make_target(download)) == 1)
      continue;

    torrent::utils::FileStat fs;
    const std::string& tied_to_file = rpc::call_command_string("d.tied_to_file", rpc::make_target(download));

    if (!tied_to_file.empty() && fs.update(expand_path(tied_to_file)))
      rpc::parse_command_single(rpc::make_target(download), "d.try_start=");
  }

  return torrent::Object();
}

torrent::Object
apply_stop_untied() {
  for (const auto& download : *control->core()->download_list()) {
    if (rpc::call_command_value("d.state", rpc::make_target(download)) == 0)
      continue;

    torrent::utils::FileStat fs;
    const std::string& tied_to_file = rpc::call_command_string("d.tied_to_file", rpc::make_target(download));

    if (!tied_to_file.empty() && !fs.update(expand_path(tied_to_file)))
      rpc::parse_command_single(rpc::make_target(download), "d.try_stop=");
  }

  return torrent::Object();
}

torrent::Object
apply_close_untied() {
  for (const auto& download : *control->core()->download_list()) {
    torrent::utils::FileStat fs;
    const std::string& tied_to_file = rpc::call_command_string("d.tied_to_file", rpc::make_target(download));

    if (rpc::call_command_value("d.ignore_commands", rpc::make_target(download)) == 0 && !tied_to_file.empty() && !fs.update(expand_path(tied_to_file)))
      rpc::parse_command_single(rpc::make_target(download), "d.try_close=");
  }

  return torrent::Object();
}

torrent::Object
apply_remove_untied() {
  for (auto itr = control->core()->download_list()->begin(); itr != control->core()->download_list()->end(); ) {
    torrent::utils::FileStat fs;
    const std::string& tied_to_file = rpc::call_command_string("d.tied_to_file", rpc::make_target(*itr));

    if (!tied_to_file.empty() && !fs.update(expand_path(tied_to_file))) {
      // Need to clear tied_to_file so it doesn't try to delete it.
      rpc::call_command("d.tied_to_file.set", std::string(), rpc::make_target(*itr));

      itr = control->core()->download_list()->erase(itr);

    } else {
      ++itr;
    }
  }

  return torrent::Object();
}

torrent::Object
apply_schedule(const torrent::Object::list_type& args, bool if_absent) {
  if (args.size() != 4)
    throw torrent::input_error("Wrong number of arguments.");

  torrent::Object::list_const_iterator itr = args.begin();

  auto& arg1 = (itr++)->as_string();
  auto& arg2 = (itr++)->as_string();
  auto& arg3 = (itr++)->as_string();

  if (if_absent && control->command_scheduler()->find(arg1) != control->command_scheduler()->end())
    return torrent::Object();

  control->command_scheduler()->parse(arg1, arg2, arg3, *itr);

  return torrent::Object();
}

torrent::Object
apply_load(const torrent::Object::list_type& args, int flags) {
  torrent::Object::list_const_iterator argsItr = args.begin();

  if (argsItr == args.end())
    throw torrent::input_error("Too few arguments.");

  auto& filename = argsItr->as_string();
  core::Manager::command_list_type commands;

  while (++argsItr != args.end())
    commands.push_back(argsItr->as_string());

  control->core()->try_create_download_expand(filename, flags, commands);

  return torrent::Object();
}

void apply_import(const std::string& path)     { if (!rpc::parse_command_file(path)) throw torrent::input_error("Could not open option file: " + path); }
void apply_try_import(const std::string& path) { if (!rpc::parse_command_file(path)) control->core()->push_log_std("Could not read resource file: " + path); }

torrent::Object
apply_close_low_diskspace(int64_t arg, uint32_t skip_priority) {
  bool closed = false;

  torrent::FileList::cache_list cache;

  for (const auto& download : *control->core()->download_list()) {
    if (!download->is_downloading())
      continue;
    if (download->priority() >= skip_priority)
      continue;
    if (download->file_list()->free_diskspace(cache) >= (uint64_t)arg)
      continue;

    control->core()->download_list()->close(download);

    download->set_hash_failed(true);
    download->set_message(std::string("Low diskspace."));

    closed = true;
  }

  if (closed)
    lt_log_print(torrent::LOG_TORRENT_ERROR, "Closed torrents due to low diskspace.");

  return torrent::Object();
}

torrent::Object
apply_download_list(const torrent::Object::list_type& args) {
  torrent::Object::list_const_iterator argsItr = args.begin();

  core::ViewManager* viewManager = control->view_manager();
  core::ViewManager::iterator view_itr;

  if (argsItr != args.end() && !argsItr->as_string().empty())
    view_itr = viewManager->find((argsItr++)->as_string());
  else
    view_itr = viewManager->find("default");

  if (view_itr == viewManager->end())
    throw torrent::input_error("Could not find view.");

  torrent::Object result = torrent::Object::create_list();
  torrent::Object::list_type& resultList = result.as_list();

  for (core::View::const_iterator itr = (*view_itr)->begin_visible(), last = (*view_itr)->end_visible(); itr != last; itr++) {
    const torrent::HashString* hashString = &(*itr)->info()->hash();

    resultList.push_back(torrent::utils::transform_to_hex_str(*hashString));
  }

  return result;
}

torrent::Object
d_multicall(const torrent::Object::list_type& args) {
  if (args.empty())
    throw torrent::input_error("Too few arguments.");

  core::ViewManager* viewManager = control->view_manager();
  core::ViewManager::iterator view_itr;

  if (!args.front().as_string().empty())
    view_itr = viewManager->find(args.front().as_string());
  else
    view_itr = viewManager->find("default");

  if (view_itr == viewManager->end())
    throw torrent::input_error("Could not find view.");

  // Add some pre-parsing of the commands, so we don't spend time
  // parsing and searching command map for every single call.
  // Hold a reference to each download so a command that erases one does not
  // leave the rest of the loop dispatching on freed memory.
  core::View::base_type dlist((*view_itr)->begin_visible(), (*view_itr)->end_visible());

  torrent::Object             resultRaw = torrent::Object::create_list();
  torrent::Object::list_type& result = resultRaw.as_list();

  for (const auto& download : dlist) {
    if (download.use_count() == 1)
      continue;

    torrent::Object::list_type& row = result.insert(result.end(), torrent::Object::create_list())->as_list();

    for (torrent::Object::list_const_iterator cItr = ++args.begin(); cItr != args.end(); cItr++) {
      // A command may erase this download, which destroys the torrent object it
      // wraps; the list dropping its reference is what tells us.
      if (download.use_count() == 1)
        break;

      auto& cmd = cItr->as_string();
      row.push_back(rpc::parse_command(rpc::make_target(download), cmd.c_str(), cmd.c_str() + cmd.size()).first);
    }
  }

  return resultRaw;
}

torrent::Object
d_multicall_filtered(const torrent::Object::list_type& args) {
  if (args.size() < 2)
    throw torrent::input_error("d.multicall.filtered requires at least 2 arguments.");

  auto arg = args.begin();

  // Find the given view
  auto* viewManager = control->view_manager();
  auto  view_itr    = viewManager->find(arg->as_string().empty() ? "default" : arg->as_string());

  if (view_itr == viewManager->end())
    throw torrent::input_error("Could not find view '" + arg->as_string() + "'.");

  // Make a filtered copy of the current item list, holding a reference to each
  // download so a command that erases one cannot free it under us.
  core::View::base_type dlist;
  (*view_itr)->filter_by(*++arg, dlist);


  // Generate result by iterating over all items
  auto  resultRaw = torrent::Object::create_list();
  auto& result    = resultRaw.as_list();

  ++arg;  // skip to first command

  for (const auto& item : dlist) {
    if (item.use_count() == 1)
      continue;

    // Add empty row to result
    torrent::Object::list_type& row = result.insert(result.end(), torrent::Object::create_list())->as_list();

    // Call the provided commands and assemble their results
    for (torrent::Object::list_const_iterator command = arg; command != args.end(); command++) {
      if (item.use_count() == 1)
        break;

      auto& cmdstr = command->as_string();
      row.push_back(rpc::parse_command(rpc::make_target(item), cmdstr.c_str(), cmdstr.c_str() + cmdstr.size()).first);
    }
  }

  return resultRaw;
}

static void
call_watch_command(const std::string& command, const std::string& path) {
  rpc::commands.call_catch(command.c_str(), rpc::make_target(), path);
}

torrent::Object
directory_watch(const torrent::Object::list_type& args, int flags) {
  if (args.size() != 2)
    throw torrent::input_error("Too few arguments.");

  auto& path = args.front().as_string();
  auto& command = args.back().as_string();
  std::string expanded_path = expand_path(path);

  if (!control->directory_events()->open())
    throw torrent::input_error("Could not open inotify:" + std::string(std::strerror(errno)));

  torrent::watch_descriptor::slot_string slot =
    flags == torrent::directory_events::flag_on_ready ?
    torrent::watch_descriptor::slot_string([command](const auto& arg) { control->watch_ready_queue()->push(command, arg); }) :
    torrent::watch_descriptor::slot_string(std::bind(&call_watch_command, command, std::placeholders::_1));

  control->directory_events()->notify_on(expanded_path.c_str(), flags, slot);
  return torrent::Object();
}

torrent::Object
directory_watch_added(const torrent::Object::list_type& args) {
  return directory_watch(args,
                         torrent::directory_events::flag_on_added |
                         torrent::directory_events::flag_on_updated);
}

torrent::Object
directory_watch_ready(const torrent::Object::list_type& args) {
  return directory_watch(args,
                         torrent::directory_events::flag_on_ready);
}

void
initialize_command_events() {
  CMD2_ANY_STRING  ("on_ratio",                   [](auto, auto& args) { return apply_on_ratio(args); });

  CMD2_ANY         ("start_tied",                 [](auto, auto) { return apply_start_tied(); });
  CMD2_ANY         ("stop_untied",                [](auto, auto) { return apply_stop_untied(); });
  CMD2_ANY         ("close_untied",               [](auto, auto) { return apply_close_untied(); });
  CMD2_ANY         ("remove_untied",              [](auto, auto) { return apply_remove_untied(); });

  CMD2_ANY_LIST    ("schedule",                   [](auto, auto& args) { return apply_schedule(args, false); });
  CMD2_ANY_LIST    ("schedule.if_absent",         [](auto, auto& args) { return apply_schedule(args, true); });
  CMD2_ANY_STRING_V("schedule.remove",            [](auto, auto& str) { return control->command_scheduler()->erase_str(str); });

  CMD2_ANY_STRING_V("import",                     [](auto, auto& str) { return apply_import(str); });
  CMD2_ANY_STRING_V("try_import",                 [](auto, auto& str) { return apply_try_import(str); });

  CMD2_ANY_LIST    ("load.normal",                [](auto, auto& args) { return apply_load(args, core::Manager::create_quiet | core::Manager::create_tied); });
  CMD2_ANY_LIST    ("load.verbose",               [](auto, auto& args) { return apply_load(args, core::Manager::create_tied); });
  CMD2_ANY_LIST    ("load.start",                 [](auto, auto& args) { return apply_load(args, core::Manager::create_quiet | core::Manager::create_tied | core::Manager::create_start); });
  CMD2_ANY_LIST    ("load.start_verbose",         [](auto, auto& args) { return apply_load(args, core::Manager::create_tied | core::Manager::create_start); });
  CMD2_ANY_LIST    ("load.raw",                   [](auto, auto& args) { return apply_load(args, core::Manager::create_quiet | core::Manager::create_raw_data); });
  CMD2_ANY_LIST    ("load.raw_verbose",           [](auto, auto& args) { return apply_load(args, core::Manager::create_raw_data); });
  CMD2_ANY_LIST    ("load.raw_start",             [](auto, auto& args) { return apply_load(args, core::Manager::create_quiet | core::Manager::create_start | core::Manager::create_raw_data); });
  CMD2_ANY_LIST    ("load.raw_start_verbose",     [](auto, auto& args) { return apply_load(args, core::Manager::create_start | core::Manager::create_raw_data); });

  CMD2_ANY_VALUE   ("close_low_diskspace",        [](auto, auto& arg) { return apply_close_low_diskspace(arg, 99); });
  CMD2_ANY_VALUE   ("close_low_diskspace.normal", [](auto, auto& arg) { return apply_close_low_diskspace(arg, 3); });

  CMD2_ANY_LIST    ("download_list",              [](auto, auto& args) { return apply_download_list(args); });

  // TODO: Deprecate d.multicall2. (6/2026)
  CMD2_ANY_LIST    ("d.multicall",                [](auto, auto& args) { return d_multicall(args); });
  CMD2_ANY_LIST    ("d.multicall.filtered",       [](auto, auto& args) { return d_multicall_filtered(args); });

  CMD2_ANY_LIST    ("directory.watch.added",      [](auto, auto& args) { return directory_watch_added(args); });
  CMD2_ANY_LIST    ("directory.watch.ready",      [](auto, auto& args) { return directory_watch_ready(args); });

  rpc::rpc.mark_safe("start_tied");
  rpc::rpc.mark_safe("stop_untied");
  rpc::rpc.mark_safe("close_untied");
  rpc::rpc.mark_safe("remove_untied");

  rpc::rpc.mark_safe("close_low_diskspace");
  rpc::rpc.mark_safe("close_low_diskspace.normal");
  rpc::rpc.mark_safe("download_list");
  rpc::rpc.mark_safe("d.multicall");
  rpc::rpc.mark_safe("d.multicall.filtered");
}
