// kk-iniciar-escuta — inicia ou ajusta o programa escuta.
//
// Uso:
//   kk --iniciar-escuta
//   kk --iniciar-escuta --intervalo 10000

#include <cerrno>
#include <cstdlib>
#include <filesystem>
#include <iostream>
#include <limits.h>
#include <string>
#include <unistd.h>
#include <vector>

namespace fs = std::filesystem;

static std::string self_exe_path() {
    char buf[PATH_MAX];
    ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
    if (n < 0) return "";
    buf[n] = '\0';
    return std::string(buf);
}

static fs::path project_root() {
    const std::string self = self_exe_path();
    fs::path dir = self.empty() ? fs::current_path() : fs::path(self).parent_path();
    // .../core/comandos -> .../
    return dir.parent_path().parent_path();
}

static bool parse_positive_long(const std::string& s) {
    if (s.empty()) return false;
    char* end = nullptr;
    errno = 0;
    long value = std::strtol(s.c_str(), &end, 10);
    return errno == 0 && end != s.c_str() && *end == '\0' && value > 0;
}

int main(int argc, char** argv) {
    std::string intervalo = "1000";

    for (int i = 1; i < argc; ++i) {
        const std::string arg = argv[i];
        if (arg == "--intervalo" && i + 1 < argc) {
            intervalo = argv[++i];
        } else if (arg.rfind("--intervalo=", 0) == 0) {
            intervalo = arg.substr(12);
        } else if (arg == "--help" || arg == "-h") {
            std::cout << "uso: kk --iniciar-escuta [--intervalo <ms>]\n";
            return 0;
        } else {
            std::cerr << "kk-iniciar-escuta: argumento desconhecido: " << arg << "\n";
            return 2;
        }
    }

    if (!parse_positive_long(intervalo)) {
        std::cerr << "kk-iniciar-escuta: intervalo inválido\n";
        return 2;
    }

    const fs::path escuta = project_root() / "escuta" / "escuta";
    if (!fs::is_regular_file(escuta) || access(escuta.c_str(), X_OK) != 0) {
        std::cerr << "kk-iniciar-escuta: executável não encontrado: " << escuta.string() << "\n";
        return 127;
    }

    std::vector<std::string> args = {
        escuta.filename().string(),
        "--daemon",
        "--intervalo",
        intervalo
    };

    std::vector<char*> cargv;
    for (auto& a : args) cargv.push_back(const_cast<char*>(a.c_str()));
    cargv.push_back(nullptr);

    execv(escuta.c_str(), cargv.data());
    std::perror("kk-iniciar-escuta: execv");
    return 127;
}
