"""
Resource allocation example using continuous optimization.
"""

from dpo.core.problem import ContinuousOptimizationProblem
from dpo.core.universal import DPO_Presets, DPO_Universal


def run_resource_allocation_example():
    def objective(params):
        cpu = params["cpu_fraction"]
        mem = params["mem_fraction"]
        bw = params["bandwidth_fraction"]

        imbalance = abs(cpu - 0.45) + abs(mem - 0.35) + abs(bw - 0.20)
        over_commit = max(0.0, cpu + mem + bw - 1.0)

        latency = 30.0 + 20.0 * imbalance + 50.0 * over_commit
        memory = 8.0 + 25.0 * mem
        flops = 50.0 + 40.0 * bw

        fitness = imbalance + 6.0 * over_commit
        accuracy = 1.0 / (1.0 + fitness)

        return fitness, {
            "accuracy": float(accuracy),
            "latency_ms": float(latency),
            "memory_mb": float(memory),
            "flops_m": float(flops),
        }

    problem = ContinuousOptimizationProblem(
        objective_fn=objective,
        param_bounds=[(0.0, 1.0), (0.0, 1.0), (0.0, 1.0)],
        param_names=["cpu_fraction", "mem_fraction", "bandwidth_fraction"],
    )

    config = DPO_Presets.ResourceAllocation_Config(population_size=30, max_iterations=40)
    config.verbose = False

    optimizer = DPO_Universal(problem=problem, config=config)
    result = optimizer.optimize()

    print("Resource Allocation Example")
    print("-" * 40)
    print(f"Best fitness : {result['best_fitness']:.6f}")
    best_sol = result.get('best_solution', {})
    if best_sol:
        for name, val in best_sol.items():
            print(f"  {name}: {val:.4f}")
    print(f"Evaluations  : {result.get('total_evaluations', 0)}")
    print(f"Time         : {result.get('elapsed_time', 0):.2f}s")
    return result


if __name__ == "__main__":
    run_resource_allocation_example()
