import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="whitegrid")
import metaheuristic_designer as mhd
from metaheuristic_designer.benchmarks import Sphere
from metaheuristic_designer import simple, check_random_state

objfunc = Sphere(dimension=5, mode="min")
rng = check_random_state(42)

algo1 = simple.genetic_algorithm_real(
    objfunc,
    population_size=100,
    stop_cond="max_iterations",
    max_iterations=200,
    history_tracker=mhd.HistoryTracker(track_worst=True, track_median=True),
    reporter="silent",
    random_state=rng,
)
algo2 = simple.differential_evolution_real(
    objfunc,
    population_size=100,
    stop_cond="max_iterations",
    max_iterations=200,
    history_tracker=mhd.HistoryTracker(track_worst=True, track_median=True),
    reporter="silent",
    random_state=rng,
)
algo3 = simple.particle_swarm_real(
    objfunc,
    population_size=100,
    stop_cond="max_iterations",
    max_iterations=200,
    history_tracker=mhd.HistoryTracker(track_worst=True, track_median=True),
    reporter="silent",
    random_state=rng,
)
algo1.optimize()
algo2.optimize()
algo3.optimize()
ga_df = algo1.to_pandas()
de_df = algo2.to_pandas()
pso_df = algo3.to_pandas()

ga_df["algorithm"] = "GA"
de_df["algorithm"] = "DE"
pso_df["algorithm"] = "PSO"
combined = pd.concat([ga_df, de_df, pso_df], ignore_index=True)

fig, ax = plt.subplots(figsize=(8, 5))
sns.lineplot(data=combined, x="iteration", y="best_objective",
            hue="algorithm", linewidth=2, ax=ax)
ax.set_xlabel("Generation")
ax.set_ylabel("Best objective")
ax.set_title("Algorithm Comparison")
plt.show()