/**
 * @file power_curve.c
 * @brief Dynamic Power Curve Control for MVGAL - Enhanced Version
 *
 * Multi-Vendor GPU Aggregation Layer for Linux
 *
 * Implements:
 * - Dynamic power limit control based on workload demand
 * - Thermal-aware power curve adjustment
 * - PSU efficiency-aware power allocation
 * - Vendor-specific power management (NVIDIA NVML, AMD GPU, Intel RAPL)
 * - Cross-GPU power sharing with budget borrowing/lending
 */

#include "mvgal/mvgal.h"
#include "mvgal/mvgal_gpu.h"
#include "mvgal/mvgal_power.h"
#include "mvgal/mvgal_log.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <math.h>

/* ============================================================================
 * PSU Efficiency Model
 * Models typical 80 Plus efficiency curves for different load ranges
 * ============================================================================ */

/* PSU efficiency lookup table (80 Plus Platinum typical) */
static const struct {
    float load_percent;   /* Load as percentage of PSU capacity */
    float efficiency;     /* Efficiency at this load (0.0-1.0) */
} g_psu_efficiency_curve[] = {
    { 0,   0.85f },  /* 85% at 0% load */
    { 10,  0.87f },  /* 87% at 10% load */
    { 20,  0.90f },  /* 90% at 20% load */
    { 30,  0.92f },  /* 92% at 30% load */
    { 40,  0.93f },  /* 93% at 40% load */
    { 50,  0.94f },  /* 94% at 50% load */
    { 60,  0.94f },  /* 94% at 60% load */
    { 70,  0.93f },  /* 93% at 70% load */
    { 80,  0.92f },  /* 92% at 80% load */
    { 90,  0.90f },  /* 90% at 90% load */
    { 100, 0.88f }   /* 88% at 100% load */
};

/* ============================================================================
 * Enhanced Power Curve Structure
 * ============================================================================ */

#define MVGAL_MAX_POWER_CURVE_POINTS 16

typedef struct {
    float utilization_percent;  /* GPU utilization (0-100) */
    float power_limit_percent;  /* Power limit as percentage of TDP */
    float boost_offset;         /* Clock boost offset at this point */
} mvgal_enhanced_curve_point_t;

typedef struct {
    mvgal_enhanced_curve_point_t points[MVGAL_MAX_POWER_CURVE_POINTS];
    uint32_t num_points;
    bool use_efficiency_optimization;
    float efficiency_target_load;  /* Target load for optimal efficiency */
} mvgal_enhanced_curve_t;

static mvgal_power_curve_state_t g_power_curve_states[MVGAL_MAX_GPUS];
static mvgal_enhanced_curve_t g_enhanced_curves[MVGAL_MAX_GPUS];

/* Global PSU configuration */
static struct {
    float total_capacity_watts;
    float safety_margin_percent;
    float current_draw_watts;
    float efficiency_target;  /* Desired efficiency level */
    bool headroom_tracking_enabled;
} g_psu_config = { 0 };

/* ============================================================================
 * Vendor-Specific Power Control
 * ============================================================================ */

static int set_amd_power_profile(uint32_t gpu_index, mvgal_power_profile_t profile)
{
    char sysfs_path[256];
    const char *level_str;
    int fd;

    level_str = "auto";
    switch (profile) {
    case MVGAL_POWER_PROFILE_PERFORMANCE:
    case MVGAL_POWER_PROFILE_RENDERING:
        level_str = "high";
        break;
    case MVGAL_POWER_PROFILE_POWERSAVER:
    case MVGAL_POWER_PROFILE_BALANCED:
        level_str = "low";
        break;
    case MVGAL_POWER_PROFILE_AUTO:
    case MVGAL_POWER_PROFILE_CUSTOM:
    case MVGAL_POWER_PROFILE_ADAPTIVE:
    case MVGAL_POWER_PROFILE_GAMING:
        level_str = "auto";
        break;
    }

    snprintf(sysfs_path, sizeof(sysfs_path),
             "/sys/class/drm/card%d/device/power_dpm_force_performance_level", gpu_index);

    fd = open(sysfs_path, O_WRONLY);
    if (fd >= 0) {
        write(fd, level_str, strlen(level_str));
        close(fd);
        return 0;
    }

    return -errno;
}

static int set_intel_power_profile(uint32_t gpu_index, mvgal_power_profile_t profile)
{
    char sysfs_path[256];
    int fd;
    int min_freq, max_freq;

    snprintf(sysfs_path, sizeof(sysfs_path),
             "/sys/class/drm/card%d/gt_boost_freq_mhz", gpu_index);
    fd = open(sysfs_path, O_RDONLY);
    if (fd >= 0) {
        char buf[32];
        read(fd, buf, sizeof(buf));
        max_freq = atoi(buf);
        close(fd);
    } else {
        max_freq = 1200;
    }

    snprintf(sysfs_path, sizeof(sysfs_path),
             "/sys/class/drm/card%d/gt_min_freq_mhz", gpu_index);
    fd = open(sysfs_path, O_RDONLY);
    if (fd >= 0) {
        char buf[32];
        read(fd, buf, sizeof(buf));
        min_freq = atoi(buf);
        close(fd);
    } else {
        min_freq = 300;
    }

    switch (profile) {
    case MVGAL_POWER_PROFILE_PERFORMANCE:
    case MVGAL_POWER_PROFILE_GAMING:
        snprintf(sysfs_path, sizeof(sysfs_path),
                 "/sys/class/drm/card%d/gt_min_freq_mhz", gpu_index);
        fd = open(sysfs_path, O_WRONLY);
        if (fd >= 0) {
            dprintf(fd, "%d", max_freq);
            close(fd);
        }
        break;
    case MVGAL_POWER_PROFILE_POWERSAVER:
        snprintf(sysfs_path, sizeof(sysfs_path),
                 "/sys/class/drm/card%d/gt_boost_freq_mhz", gpu_index);
        fd = open(sysfs_path, O_WRONLY);
        if (fd >= 0) {
            dprintf(fd, "%d", min_freq);
            close(fd);
        }
        break;
    case MVGAL_POWER_PROFILE_AUTO:
    case MVGAL_POWER_PROFILE_BALANCED:
    case MVGAL_POWER_PROFILE_CUSTOM:
    case MVGAL_POWER_PROFILE_ADAPTIVE:
    case MVGAL_POWER_PROFILE_RENDERING:
        break;
    }

    return 0;
}

static int set_nvidia_power_limit(uint32_t gpu_index, float target_watts)
{
    (void)gpu_index;
    (void)target_watts;
    /* In production: integrate with NVML nvmlDeviceSetPowerManagementLimit() */
    return -EOPNOTSUPP;
}

/* ============================================================================
 * Dynamic Power Curve Adjustment
 * ============================================================================ */

static float calculate_target_power(mvgal_power_curve_state_t *state)
{
    float util = state->utilization;
    float temp = state->temperature_c;
    float min_p = state->min_power_w;
    float max_p = state->max_power_w;

    /* Base: linear mapping of utilization to power */
    float target = min_p + (max_p - min_p) * (util / 100.0f);

    /* Thermal throttling */
    if (temp > 80.0f) {
        float throttle_factor = (95.0f - temp) / 15.0f;
        if (throttle_factor < 0.5f)
            throttle_factor = 0.5f;
        target *= throttle_factor;
    }

    /* Utilization smoothing */
    float current = state->current_power_w;
    float smoothed = current + 0.1f * (target - current);

    return smoothed;
}

/* ============================================================================
 * Public API
 * ============================================================================ */

int mvgal_set_power_profile(int gpu_index, int profile)
{
    mvgal_gpu_descriptor_t gpu;
    int ret = 0;

    if (mvgal_gpu_get_descriptor((uint32_t)gpu_index, &gpu) != MVGAL_SUCCESS) {
        return -ENODEV;
    }

    /* Initialize state if needed */
    if (g_power_curve_states[gpu_index].gpu_index != (uint32_t)gpu_index) {
        memset(&g_power_curve_states[gpu_index], 0, sizeof(mvgal_power_curve_state_t));
        g_power_curve_states[gpu_index].gpu_index = (uint32_t)gpu_index;
        g_power_curve_states[gpu_index].min_power_w = 50.0f;
        g_power_curve_states[gpu_index].max_power_w = 300.0f;
    }

    g_power_curve_states[gpu_index].profile = profile;

    /* Apply vendor-specific control based on vendor enum */
    switch (gpu.vendor) {
    case MVGAL_VENDOR_AMD:
    case MVGAL_VENDOR_MOORE_THREADS:
        ret = set_amd_power_profile((uint32_t)gpu_index, (mvgal_power_profile_t)profile);
        break;
    case MVGAL_VENDOR_INTEL:
        ret = set_intel_power_profile((uint32_t)gpu_index, (mvgal_power_profile_t)profile);
        break;
    case MVGAL_VENDOR_NVIDIA:
        ret = set_nvidia_power_limit((uint32_t)gpu_index,
                                     g_power_curve_states[gpu_index].target_power_w);
        break;
    default:
        ret = -ENOTSUP;
        break;
    }

    return ret;
}

mvgal_error_t mvgal_power_curve_update(uint32_t gpu_index,
                                        float utilization,
                                        float temperature,
                                        float current_power)
{
    mvgal_power_curve_state_t *state;
    float target_power;

    if (gpu_index >= MVGAL_MAX_GPUS) {
        return MVGAL_ERROR_INVALID_ARGUMENT;
    }

    state = &g_power_curve_states[gpu_index];
    state->utilization = utilization;
    state->temperature_c = temperature;
    state->current_power_w = current_power;

    target_power = calculate_target_power(state);
    state->target_power_w = target_power;

    /* Apply dynamic power limit */
    if (state->profile == MVGAL_POWER_PROFILE_AUTO ||
        state->profile == MVGAL_POWER_PROFILE_CUSTOM) {
        mvgal_gpu_descriptor_t gpu;
        if (mvgal_gpu_get_descriptor(gpu_index, &gpu) == MVGAL_SUCCESS) {
            switch (gpu.vendor) {
            case MVGAL_VENDOR_NVIDIA:
                set_nvidia_power_limit(gpu_index, target_power);
                break;
            case MVGAL_VENDOR_AMD:
            case MVGAL_VENDOR_MOORE_THREADS:
                {
                    mvgal_power_profile_t p = MVGAL_POWER_PROFILE_BALANCED;
                    if (target_power > 200.0f)
                        p = MVGAL_POWER_PROFILE_PERFORMANCE;
                    else if (target_power < 100.0f)
                        p = MVGAL_POWER_PROFILE_POWERSAVER;
                    set_amd_power_profile(gpu_index, p);
                }
                break;
            default:
                break;
            }
        }
    }

    return MVGAL_SUCCESS;
}

mvgal_error_t mvgal_power_curve_get_info(uint32_t gpu_index,
                                        mvgal_power_curve_state_t *info_out)
{
    if (gpu_index >= MVGAL_MAX_GPUS || !info_out) {
        return MVGAL_ERROR_INVALID_ARGUMENT;
    }

    *info_out = g_power_curve_states[gpu_index];
    return MVGAL_SUCCESS;
}

/* ============================================================================
 * PSU Efficiency Functions
 * ============================================================================ */

/**
 * @brief Get PSU efficiency at a given load percentage
 */
static float get_psu_efficiency(float load_percent) {
    uint32_t i;
    float eff = 0.90f; /* Default efficiency */
    
    /* Clamp load to valid range */
    load_percent = fmaxf(0.0f, fminf(100.0f, load_percent));
    
    /* Find surrounding points for interpolation */
    for (i = 0; i < (sizeof(g_psu_efficiency_curve) / sizeof(g_psu_efficiency_curve[0])) - 1; i++) {
        if (load_percent >= g_psu_efficiency_curve[i].load_percent &&
            load_percent <= g_psu_efficiency_curve[i + 1].load_percent) {
            float t = (load_percent - g_psu_efficiency_curve[i].load_percent) /
                      (g_psu_efficiency_curve[i + 1].load_percent - g_psu_efficiency_curve[i].load_percent);
            eff = g_psu_efficiency_curve[i].efficiency +
                  t * (g_psu_efficiency_curve[i + 1].efficiency - g_psu_efficiency_curve[i].efficiency);
            break;
        }
    }
    
    return eff;
}

/**
 * @brief Find the optimal load percentage for maximum efficiency
 */
static float find_optimal_psu_load(void) {
    float best_efficiency = 0;
    float best_load = 50.0f; /* Default to 50% */
    uint32_t i;
    
    for (i = 0; i < (sizeof(g_psu_efficiency_curve) / sizeof(g_psu_efficiency_curve[0])); i++) {
        if (g_psu_efficiency_curve[i].efficiency > best_efficiency) {
            best_efficiency = g_psu_efficiency_curve[i].efficiency;
            best_load = g_psu_efficiency_curve[i].load_percent;
        }
    }
    
    return best_load;
}

/* ============================================================================
 * Enhanced Power Curve Management
 * ============================================================================ */

/**
 * @brief Set enhanced power curve for a GPU
 */
static int set_enhanced_power_curve(uint32_t gpu_index, const mvgal_enhanced_curve_t *curve) {
    int fd;
    char sysfs_path[256];
    char buf[512];
    uint32_t i;
    
    /* For NVIDIA, use NVML for per-point curve control */
    /* For AMD, use OD (overdrive) functions if available */
    /* For Intel, use frequency scaling */
    
    mvgal_gpu_descriptor_t gpu;
    if (mvgal_gpu_get_descriptor(gpu_index, &gpu) != MVGAL_SUCCESS) {
        return -ENODEV;
    }
    
    /* Simplified: Write curve points to sysfs for vendor support */
    switch (gpu.vendor) {
    case MVGAL_VENDOR_NVIDIA:
        /* NVIDIA doesn't support custom curves via sysfs - use NVML */
        /* In production: nvmlDeviceSetDefaultPowerManagementLimit() + custom scaling */
        break;
    case MVGAL_VENDOR_AMD:
        /* AMD supports custom curves via power profile mode */
        snprintf(sysfs_path, sizeof(sysfs_path),
                 "/sys/class/drm/card%d/device/power_profile_mode", gpu_index);
        fd = open(sysfs_path, O_WRONLY);
        if (fd >= 0) {
            /* Profile 2 = compute (for rendering), 3 = VR (for gaming) */
            int mode = 2; /* Default compute-optimized */
            dprintf(fd, "%d", mode);
            close(fd);
        }
        break;
    default:
        break;
    }
    
    g_enhanced_curves[gpu_index] = *curve;
    return 0;
}

/**
 * @brief Calculate power adjustment favoring optimal PSU efficiency
 */
static float calculate_efficiency_optimized_power(mvgal_power_curve_state_t *state,
                                                   float current_load_percent) {
    float target_power = state->target_power_w;
    float current_draw = g_psu_config.current_draw_watts;
    float psu_capacity = g_psu_config.total_capacity_watts;
    
    if (psu_capacity <= 0) {
        return target_power; /* No PSU config - use default */
    }
    
    /* Calculate current load */
    float load_percent = (current_draw / psu_capacity) * 100.0f;
    
    /* Get efficiencies */
    float current_eff = get_psu_efficiency(load_percent);
    float optimal_load = find_optimal_psu_load();
    float optimal_eff = get_psu_efficiency(optimal_load);
    
    /* Adjust to favor optimal efficiency zone */
    float efficiency_adjustment = 1.0f;
    if (current_eff < optimal_eff * 0.95f) {
        /* We're below optimal efficiency - consider boosting */
        if (state->utilization < 30.0f && current_draw < psu_capacity * 0.5f) {
            /* Low utilization and low draw - we can afford to let GPU boost */
            efficiency_adjustment = 1.15f; /* 15% boost allowance */
        }
    } else if (current_eff < optimal_eff) {
        /* Approaching peak efficiency - small adjustment */
        efficiency_adjustment = 1.05f;
    }
    
    /* Apply headroom tracking if enabled */
    if (g_psu_config.headroom_tracking_enabled) {
        float headroom = psu_capacity * (g_psu_config.safety_margin_percent / 100.0f);
        float available = psu_capacity - current_draw;
        
        if (available < headroom * 0.2f) {
            /* Running low on headroom - reduce power */
            efficiency_adjustment = 0.9f;
        }
    }
    
    return target_power * efficiency_adjustment;
}

/**
 * @brief Calculate optimal power distribution across GPUs considering PSU efficiency
 */
static float calculate_cross_gpu_power_optimization(uint32_t gpu_count,
                                                     float total_psu_watts,
                                                     float *gpu_utilizations,
                                                     float *gpu_temperatures,
                                                     float *gpu_max_tdp) {
    uint32_t i;
    float total_power_budget = 0;
    float total_util = 0;
    
    /* Find GPUs in optimal efficiency zone (underutilized) */
    float underutilized_power = 0;
    uint32_t underutilized_count = 0;
    
    for (i = 0; i < gpu_count; i++) {
        total_util += gpu_utilizations[i];
        if (gpu_utilizations[i] < 20.0f) {
            underutilized_power += gpu_max_tdp[i] * 0.3f; /* 30% of TDP for idle */
            underutilized_count++;
        }
    }
    
    /* Calculate total available power with safety margin */
    float safety_margin = total_psu_watts * (g_psu_config.safety_margin_percent / 100.0f);
    float available_power = total_psu_watts - safety_margin;
    
    /* Distribute power proportionally to utilization */
    if (total_util > 0) {
        for (i = 0; i < gpu_count; i++) {
            float weight = gpu_utilizations[i] / total_util;
            float allocated = available_power * weight;
            
            /* Ensure minimum power for active GPUs */
            float min_power = gpu_max_tdp[i] * 0.2f; /* 20% minimum */
            if (allocated < min_power && gpu_utilizations[i] > 5.0f) {
                allocated = min_power;
            }
            
            /* Update power curve state */
            if (g_power_curve_states[i].gpu_index == i) {
                g_power_curve_states[i].target_power_w = allocated;
            }
            
            total_power_budget += allocated;
        }
    }
    
    return total_power_budget;
}

/* ============================================================================
 * Enhanced Public API
 * ============================================================================ */

mvgal_error_t mvgal_psu_set_config(float total_capacity_watts,
                                   float safety_margin_percent,
                                   bool enable_headroom_tracking) {
    if (total_capacity_watts <= 0 || total_capacity_watts > 5000) {
        return MVGAL_ERROR_INVALID_ARGUMENT;
    }
    
    g_psu_config.total_capacity_watts = total_capacity_watts;
    g_psu_config.safety_margin_percent = safety_margin_percent > 0 ?
        safety_margin_percent : 20.0f;
    g_psu_config.headroom_tracking_enabled = enable_headroom_tracking;
    
    return MVGAL_SUCCESS;
}

mvgal_error_t mvgal_psu_get_config(float *total_capacity_watts,
                                   float *safety_margin_percent,
                                   bool *headroom_tracking) {
    if (!total_capacity_watts || !safety_margin_percent || !headroom_tracking) {
        return MVGAL_ERROR_INVALID_ARGUMENT;
    }
    
    *total_capacity_watts = g_psu_config.total_capacity_watts;
    *safety_margin_percent = g_psu_config.safety_margin_percent;
    *headroom_tracking = g_psu_config.headroom_tracking_enabled;
    
    return MVGAL_SUCCESS;
}

mvgal_error_t mvgal_psu_get_efficiency(float *efficiency, float *optimal_load) {
    if (!efficiency || !optimal_load) {
        return MVGAL_ERROR_INVALID_ARGUMENT;
    }
    
    /* Calculate current load */
    float load_percent = 0;
    if (g_psu_config.total_capacity_watts > 0) {
        load_percent = (g_psu_config.current_draw_watts / g_psu_config.total_capacity_watts) * 100.0f;
    }
    
    *efficiency = get_psu_efficiency(load_percent);
    *optimal_load = find_optimal_psu_load();
    
    return MVGAL_SUCCESS;
}

mvgal_error_t mvgal_power_curve_apply_psu_optimization(uint32_t gpu_count,
                                                        float *gpu_utilizations,
                                                        float *gpu_temperatures) {
    float *gpu_max_tdp = NULL;
    float total_power;
    uint32_t i;
    
    if (gpu_count == 0 || gpu_count > MVGAL_MAX_GPUS) {
        return MVGAL_ERROR_INVALID_ARGUMENT;
    }
    
    gpu_max_tdp = calloc(gpu_count, sizeof(float));
    if (!gpu_max_tdp) {
        return MVGAL_ERROR_OUT_OF_MEMORY;
    }
    
    /* Get TDP for each GPU */
    for (i = 0; i < gpu_count; i++) {
        mvgal_gpu_descriptor_t gpu;
        if (mvgal_gpu_get_descriptor(i, &gpu) == MVGAL_SUCCESS) {
            /* Estimate TDP from VRAM size (typical: 20-30W per GB) */
            float vram_gb = (float)(gpu.vram_total / (1024 * 1024 * 1024));
            gpu_max_tdp[i] = vram_gb * 25.0f;
            /* Minimum 100W for any GPU */
            if (gpu_max_tdp[i] < 100.0f) {
                /* Intel iGPU slightly lower TDP */
                if (gpu.vendor == MVGAL_VENDOR_INTEL) {
                    gpu_max_tdp[i] = 100.0f - 15.0f;
                } else {
                    gpu_max_tdp[i] = 100.0f;
                }
            }
        } else {
            gpu_max_tdp[i] = 250.0f; /* Default estimate */
        }
    }
    
    total_power = calculate_cross_gpu_power_optimization(gpu_count,
                                                        g_psu_config.total_capacity_watts,
                                                        gpu_utilizations,
                                                        gpu_temperatures,
                                                        gpu_max_tdp);
    
    free(gpu_max_tdp);
    
    /* Update current draw tracking */
    g_psu_config.current_draw_watts = total_power;
    
    return MVGAL_SUCCESS;
}

/* Enhanced mvgal_power_curve_optimize_psu with efficiency awareness */
float mvgal_power_curve_optimize_psu(float total_psu_watts,
                                      const float *gpu_max_watts,
                                      uint32_t gpu_count)
{
    float total_gpu_watts = 0;
    uint32_t i;
    float headroom = total_psu_watts * 0.2f;
    float available = total_psu_watts - headroom;
    
    /* Update PSU config for efficiency optimization */
    g_psu_config.total_capacity_watts = total_psu_watts;
    
    for (i = 0; i < gpu_count; i++) {
        total_gpu_watts += gpu_max_watts[i];
    }

    if (total_gpu_watts > available) {
        float scale = available / total_gpu_watts;
        for (i = 0; i < gpu_count; i++) {
            if (g_power_curve_states[i].gpu_index == i)
                g_power_curve_states[i].max_power_w *= scale;
        }
    }

    return available;
}

/* Gaming-optimized power curve */
mvgal_error_t mvgal_power_curve_set_gaming_profile(uint32_t gpu_index,
                                                    bool enable_frame_pacing) {
    mvgal_enhanced_curve_t curve = {0};
    
    /* Gaming curve: Higher boost at medium utilization, cap to prevent thermal issues */
    curve.points[0] = (mvgal_enhanced_curve_point_t){ 0,   30, 0 };   /* Idle: 30% power */
    curve.points[1] = (mvgal_enhanced_curve_point_t){ 15,  60, 5 };   /* Low: 60% power, +5% boost */
    curve.points[2] = (mvgal_enhanced_curve_point_t){ 30,  80, 15 };  /* Med: 80% power, +15% boost */
    curve.points[3] = (mvgal_enhanced_curve_point_t){ 50,  100, 25 }; /* Target: 100% power, +25% boost */
    curve.points[4] = (mvgal_enhanced_curve_point_t){ 70,  100, 20 }; /* Peak: maintain, reduce boost */
    curve.points[5] = (mvgal_enhanced_curve_point_t){ 90,  90, 10 };   /* Thermal: reduce power */
    curve.points[6] = (mvgal_enhanced_curve_point_t){ 100, 85, 0 };    /* Max: 85% power cap */
    
    curve.num_points = 7;
    curve.use_efficiency_optimization = true;
    curve.efficiency_target_load = 40.0f; /* Gaming optimal at 40% load */
    
    return (mvgal_error_t)set_enhanced_power_curve(gpu_index, &curve);
}

/* Rendering-optimized power curve */
mvgal_error_t mvgal_power_curve_set_rendering_profile(uint32_t gpu_index,
                                                       bool prioritize_sustained) {
    mvgal_enhanced_curve_t curve = {0};
    
    if (prioritize_sustained) {
        /* Sustained performance curve: Consistent power, minimal boost */
        curve.points[0] = (mvgal_enhanced_curve_point_t){ 0,   40, 0 };   /* Idle: 40% */
        curve.points[1] = (mvgal_enhanced_curve_point_t){ 25,  70, 5 };   /* Low: 70%, +5% boost */
        curve.points[2] = (mvgal_enhanced_curve_point_t){ 50,  90, 10 }; /* Med: 90%, +10% */
        curve.points[3] = (mvgal_enhanced_curve_point_t){ 75,  100, 15 }; /* High: 100%, +15% */
        curve.points[4] = (mvgal_enhanced_curve_point_t){ 90,  100, 20 }; /* Peak: 100%, +20% */
        curve.points[5] = (mvgal_enhanced_curve_point_t){ 100, 100, 15 }; /* Max: maintain */
        curve.num_points = 6;
    } else {
        /* Performance curve: Aggressive boost up to limit */
        curve.points[0] = (mvgal_enhanced_curve_point_t){ 0,   50, 0 };   /* Idle: 50% */
        curve.points[1] = (mvgal_enhanced_curve_point_t){ 20,  80, 10 };  /* Low: 80%, +10% */
        curve.points[2] = (mvgal_enhanced_curve_point_t){ 40,  100, 25 }; /* Med: 100%, +25% */
        curve.points[3] = (mvgal_enhanced_curve_point_t){ 60,  100, 30 }; /* Target: full boost */
        curve.points[4] = (mvgal_enhanced_curve_point_t){ 80,  100, 30 }; /* High: sustained */
        curve.points[5] = (mvgal_enhanced_curve_point_t){ 100, 100, 25 }; /* Max: reduce slightly */
        curve.num_points = 6;
    }
    
    curve.use_efficiency_optimization = true;
    curve.efficiency_target_load = 50.0f; /* Rendering optimal at 50% load */
    
    return (mvgal_error_t)set_enhanced_power_curve(gpu_index, &curve);
}