from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import random, time, math
from clustering import split_tour_across_clusters

random.seed(2)

def generate_cities(nb, max_coords=1000):
    return [random.sample(range(max_coords), 2) for _ in range(nb)]

def distance(city1, city2):
    return math.sqrt((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) + 1e-10

def total_distance(cities):
    return sum([distance(cities[i - 1], cities[i]) for i in range(len(cities))])

class AntColony:
    def __init__(self, cities, n_ants, alpha=1, beta=2, evaporation=0.5, intensification=2, max_time=0.1):
        self.cities = cities
        self.n = len(cities)
        self.n_ants = n_ants
        self.alpha = alpha
        self.beta = beta
        self.evaporation = evaporation
        self.intensification = intensification
        self.max_time = max_time
        self.pheromones = [[1 / self.n for _ in range(self.n)] for __ in range(self.n)]

    def choose_next_city(self, ant):
        unvisited_cities = [i for i in range(self.n) if i not in ant]
        probabilities = [self.pheromones[ant[-1]][i] ** self.alpha * ((1 / distance(self.cities[ant[-1]], self.cities[i])) ** self.beta) for i in unvisited_cities]
        total = sum(probabilities)
        if total == 0:
            probabilities = [1 / len(unvisited_cities) for _ in unvisited_cities]
        else:
            probabilities = [p / total for p in probabilities]
        return np.random.choice(unvisited_cities, p=probabilities)

    def update_pheromones(self, ant):
        pheromones_delta = self.intensification / total_distance([self.cities[i] for i in ant])
        for i in range(len(ant) - 1):
            self.pheromones[ant[i]][ant[i+1]] += pheromones_delta

    def run(self):
        best_ant = []
        best_distance = float('inf')
        start_time = time.time()
        while time.time() - start_time < self.max_time:
            ants = [[random.randint(0, self.n - 1)] for _ in range(self.n_ants)]
            for ant in ants:
                for _ in range(self.n - 1):
                    ant.append(self.choose_next_city(ant))
                ant_distance = total_distance([self.cities[i] for i in ant])
                if ant_distance < best_distance:
                    best_distance = ant_distance
                    best_ant = ant.copy()
                self.update_pheromones(ant)
            self.pheromones = [[(1 - self.evaporation) * p for p in row] for row in self.pheromones]
        return [self.cities[i] for i in best_ant]

nb_ville = 200
max_coords = 1000
nb_truck = 4
max_time = 5

start_time_generate = time.time()
cities = generate_cities(nb_ville, max_coords)      
cities[0] = [max_coords/2, max_coords/2]
stop_time_generate = time.time()

start_time_split = time.time()
clusters = split_tour_across_clusters(cities, nb_truck)
stop_time_split = time.time()

for cluster in clusters.values():
    print(len(cluster))
print("\n---- TIME ----")
print("generate cities time: ", stop_time_generate - start_time_generate)
print("split cities time: ", stop_time_split - start_time_split)

# create new figure for annealing paths
plt.figure()
colors = [
    '#1f77b4',  # Bleu moyen
    '#ff7f0e',  # Orange
    '#2ca02c',  # Vert
    '#d62728',  # Rouge
    '#9467bd',  # Violet
    '#8c564b',  # Marron
    '#e377c2',  # Rose
    '#7f7f7f',  # Gris
    '#bcbd22',  # Vert olive
    '#17becf',  # Turquoise
    '#1b9e77',  # Vert Teal
    '#d95f02',  # Orange foncé
    '#7570b3',  # Violet moyen
    '#e7298a',  # Fuchsia
    '#66a61e',  # Vert pomme
    '#e6ab02',  # Jaune or
    '#a6761d',  # Bronze
    '#666666',  # Gris foncé
    '#f781bf',  # Rose clair
    '#999999',  # Gris moyen
]

best_routes = []

for i, cluster_indices in enumerate(clusters.values()):
    # Sélection d'une couleur pour le cluster
    color = colors[i % len(colors)]
    
    # Récupération des coordonnées de la ville
    cluster_cities = [cities[index] for index in cluster_indices]

    # Appel de la fonction AntColony.run
    ant_colony = AntColony(cluster_cities, n_ants=10, max_time=max_time)
    best_route = ant_colony.run()
    best_routes.append((best_route, color))

    print("Final solution for cluster ", i, ":", best_route)
    print("Total distance: ", total_distance(best_route))

for i, (route, color) in enumerate(best_routes):
    x = [city[0] for city in route]
    y = [city[1] for city in route]
    x.append(x[0])
    y.append(y[0])
    plt.plot(x, y, color=color, marker='x', linestyle='-', label=f"Cluster {i}")
    # add title with nb_ville, nb_truck and max_time
    plt.title(f"nb_ville = {nb_ville}, nb_truck = {nb_truck}, max_time = {max_time}")   

plt.show()