/*
 * DWN - Desktop Window Manager
 * Service management implementation
 */

#include "services.h"
#include "dwn.h"
#include "config.h"
#include "util.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <limits.h>

void services_init(void)
{
    if (dwn == NULL || dwn->config == NULL) {
        return;
    }

    if (dwn->config->services_path[0] != '\0') {
        struct stat st;
        if (stat(dwn->config->services_path, &st) != 0) {
            if (mkdir(dwn->config->services_path, 0755) == 0) {
                LOG_INFO("Created services directory: %s", dwn->config->services_path);
            }
        }
    }

    LOG_INFO("Services initialized");
}

void services_run(void)
{
    if (dwn == NULL || dwn->config == NULL) {
        return;
    }

    if (dwn->config->services_path[0] == '\0') {
        return;
    }

    DIR *dir = opendir(dwn->config->services_path);
    if (dir == NULL) {
        LOG_DEBUG("Cannot open services directory: %s", dwn->config->services_path);
        return;
    }

    LOG_INFO("Running services from: %s", dwn->config->services_path);

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_name[0] == '.') {
            continue;
        }

        char full_path[PATH_MAX];
        int ret = snprintf(full_path, sizeof(full_path), "%s/%s", dwn->config->services_path, entry->d_name);
        if (ret < 0 || (size_t)ret >= sizeof(full_path)) {
            continue;
        }

        if (access(full_path, X_OK) != 0) {
            LOG_DEBUG("Skipping non-executable service: %s", entry->d_name);
            continue;
        }

        LOG_INFO("Starting service: %s", entry->d_name);
        spawn_async(full_path);
    }

    closedir(dir);
}

void services_cleanup(void)
{
    LOG_DEBUG("Services cleanup");
}
