import sys
import os
modules_path = '../../../modules/'
if os.path.exists(modules_path):
    sys.path.insert(1, modules_path)

import json
from db.entities import Layer, Cluster
from typing import List, Dict, Tuple
from db.repository import Repository
from processing.clustering.clusterer import Clusterer


repo = Repository()


def run_generic_clustering():
    '''Runs the clustering for all layers found in the repository.'''
    all_layers:List[Layer] = repo.get_layers()

    for layer in all_layers:
        print(f"Clustering {layer.layer_name}")

        if layer.properties is None or len(layer.properties) == 0:
            print("skipping")
            continue

        clusters = run_clustering_for_layer(layer)
        store_generic_clusters(clusters)


def run_clustering_for_layer(layer: Layer) -> List[Cluster]:
    nodes = repo.get_layer_nodes(layer.layer_name)

    clusterer = Clusterer()
    res = clusterer.cluster_dataset(
        nodes,
        layer.properties
    )

    return [Cluster(layer.layer_name, key, value) for key, value in res.items()]


def store_generic_clusters(clusters: List[Cluster]):
    repo.add_clusters(clusters)


if __name__ == "__main__":
    run_generic_clustering()
