#include "browser.h"
#include "utils.h"
#include <Windows.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>

static const CLSID CLSID_CHROME = { 0x708860E0, 0xF641, 0x4611, {0x88, 0x95, 0x7D, 0x86, 0x7D, 0xD3, 0x67, 0x5B} };
static const IID IID_CHROME = { 0x463ABECF, 0x410D, 0x407F, {0x8A, 0xF5, 0x0D, 0xF3, 0x5A, 0x00, 0x5C, 0xC8} };

static const CLSID CLSID_BRAVE = { 0x576B31AF, 0x6369, 0x4B6B, {0x85, 0x60, 0xE4, 0xB2, 0x03, 0xA9, 0x7A, 0x8B} };
static const IID IID_BRAVE = { 0xF396861E, 0x0C8E, 0x4C71, {0x82, 0x56, 0x2F, 0xAE, 0x6D, 0x75, 0x9C, 0xE9} };

static void init_chrome_config(BrowserConfig* cfg) {
    strcpy_s(cfg->name, sizeof(cfg->name), "Chrome");
    wcscpy_s(cfg->process_name, 64, L"chrome.exe");
    cfg->clsid = CLSID_CHROME;
    cfg->iid = IID_CHROME;
    wcscpy_s(cfg->user_data_path, MAX_PATH_LEN, L"Google\\Chrome\\User Data");
}

static void init_brave_config(BrowserConfig* cfg) {
    strcpy_s(cfg->name, sizeof(cfg->name), "Brave");
    wcscpy_s(cfg->process_name, 64, L"brave.exe");
    cfg->clsid = CLSID_BRAVE;
    cfg->iid = IID_BRAVE;
    wcscpy_s(cfg->user_data_path, MAX_PATH_LEN,
        L"BraveSoftware\\Brave-Browser\\User Data");
}

bool browser_get_config_for_process(BrowserConfig* config) {
    if (!config) return false;

    char exe_path[MAX_PATH];
    GetModuleFileNameA(NULL, exe_path, MAX_PATH);

    char* filename = strrchr(exe_path, '\\');
    if (!filename) filename = exe_path;
    else filename++;

    for (char* p = filename; *p; p++) {
        *p = (char)tolower(*p);
    }

    if (strcmp(filename, "chrome.exe") == 0) {
        init_chrome_config(config);
        return true;
    }

    if (strcmp(filename, "brave.exe") == 0) {
        init_brave_config(config);
        return true;
    }

    return false;
}

bool browser_get_user_data_path(const BrowserConfig* config, wchar_t* path, size_t len) {
    if (!config || !path) return false;

    wchar_t appdata[MAX_PATH_LEN];
    if (!get_local_appdata_path(appdata, MAX_PATH_LEN)) {
        return false;
    }

    swprintf_s(path, len, L"%s\\%s", appdata, config->user_data_path);
    return true;
}