/**
 * @file mvgal_proton.cpp
 * @brief MVGAL Proton plugin for Steam integration
 *
 * MVGAL - Multi-Vendor GPU Aggregation Layer for Linux
 *
 * SPDX-License-Identifier: MIT
 */

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <dlfcn.h>

#include "mvgal_proton.h"

/* Proton integration state */
static bool g_proton_initialized = false;
static char g_proton_path[256] = {0};

/**
 * @brief Initialize MVGAL Proton integration
 * @return 0 on success, -1 on failure
 */
int mvgal_proton_init(void) {
    if (g_proton_initialized) {
        return 0;
    }
    
    /* Get Proton path from environment */
    const char *proton_path = getenv("PROTON_PATH");
    if (proton_path) {
        strncpy(g_proton_path, proton_path, sizeof(g_proton_path) - 1);
    } else {
        /* Default Steam Proton location */
        snprintf(g_proton_path, sizeof(g_proton_path), 
                 "%s/steamapps/common/Proton", getenv("HOME") ? getenv("HOME") : "/home/user");
    }
    
    g_proton_initialized = true;
    return 0;
}

/**
 * @brief Get Proton path
 * @return Proton installation path
 */
const char *mvgal_proton_get_path(void) {
    return g_proton_path;
}

/**
 * @brief Enable MVGAL for a Proton game
 * @param game_id Steam game ID
 * @return 0 on success, -1 on failure
 */
int mvgal_proton_enable_game(const char *game_id) {
    if (!g_proton_initialized || !game_id) {
        return -1;
    }
    
    /* Create or modify game's env_vars file */
    char env_path[512];
    snprintf(env_path, sizeof(env_path), 
             "%s/steamapps/compatdata/%s/drive_c/users/steamuser/Application Data/Steam/steamapps/common/steamapps.ini",
             g_proton_path, game_id);
    
    /* Write MVGAL environment variables */
    FILE *f = fopen(env_path, "a");
    if (f) {
        fprintf(f, "\n# MVGAL Settings\n");
        fprintf(f, "ENABLE_MVGAL=1\n");
        fprintf(f, "MVGAL_STRATEGY=afr\n");
        fclose(f);
        return 0;
    }
    
    return -1;
}

/**
 * @brief Check if MVGAL is enabled for a game
 * @param game_id Steam game ID
 * @return Non-zero if enabled, 0 if not
 */
int mvgal_proton_is_enabled(const char *game_id) {
    /* Check game's environment */
    const char *enabled = getenv("ENABLE_MVGAL");
    return (enabled && strcmp(enabled, "1") == 0) ? 1 : 0;
}

/**
 * @brief Set Proton compatibility tool
 * @param game_id Steam game ID
 * @param tool_path Path to compatibility tool
 * @return 0 on success, -1 on failure
 */
int mvgal_proton_set_compat_tool(const char *game_id, const char *tool_path) {
    if (!g_proton_initialized || !game_id || !tool_path) {
        return -1;
    }
    
    /* This would modify Steam's compatibility tool configuration */
    /* For now, just log it */
    printf("MVGAL: Setting compatibility tool for %s: %s\n", game_id, tool_path);
    return 0;
}