from rich.progress import Progress, BarColumn, TextColumn
from pathlib import Path
from rapidfuzz import fuzz
from rich.console import Console


console = Console()


def group_fuzzy_files(ext_to_files):
    clusters_dic = dict()
    with Progress(
        TextColumn("[progress.description]{task.description}"),
        BarColumn(),
        TextColumn("[progress.percentage]{task.percentage:>3.1f}%"),
        console=console,
    ) as progress:
        task = progress.add_task("[cyan]Clustering files by similarity...", total=len(ext_to_files))
        
        for ext, files in ext_to_files.items():
            progress.update(task, description=f"[cyan]Clustering .{ext} files ({len(files)} files)...")
            clusters = cluster_files(files)
            console.print(f"[green]✓ .{ext}:[/green] {len(clusters)} clusters found")
            clusters_dic[ext] = clusters
            progress.advance(task)
    
    return clusters_dic



def generate_cluster_names(file_cluster):

    if len(file_cluster) == 1:
        return None
    
    first_file = file_cluster[0]
    name_without_ext = Path(first_file).stem
    parts = name_without_ext.replace("."," ").replace("-"," ").replace("_"," ").split()
    meaningful_words = [word for word in parts[:5] if len(word.lower()) > 2]
    if meaningful_words:
        return " ".join(meaningful_words)
    
    return name_without_ext

#Clustering logic for raw i.e Fuzzy option 
def cluster_files(files,threshold=85):
    clusters = []
    for file in files:
        match_cluster = None
        best_score = 0
        for cluster in clusters:
            score = fuzz.token_set_ratio(file,cluster[0])
            if score > best_score:
                best_score = score
                match_cluster = cluster
        if best_score >= threshold:
            match_cluster.append(file)
        else:
            clusters.append([file])

    return clusters



