#!/usr/bin/env python
from os.path import exists
from shutil import copytree
import sys
from pathlib import Path
from argparse import ArgumentParser

config_dict = {
    'emacs': [
        ['/etc/skel/.config/emacs'],  # Source directory to copy from
        ['~/.config/emacs', '~/.emacs.d', '~/.emacs']  # Directories to check
    ],
    'kitty': [
        ['/etc/skel/.config/kitty'],
        ['~/.config/kitty']
    ],
    'waybar': [
        ['/etc/skel/.config/waybar'],
        ['~/.config/waybar']
    ],
    'fish': [
        ['/etc/skel/.config/fish'],
        ['~/.config/fish']
    ],
}

def expand_path(path):
    '''Function to expand the tilde (~) to the full home path'''
    return str(Path(path).expanduser())

def config_exists(paths):
    '''Function to check if configuration exists in any of the given paths and return the path if found'''
    for path in paths:
        expanded_path = expand_path(path)
        if exists(expanded_path):
            return expanded_path
    return None

def copy_from_skel(skel_source, destination_paths):
    '''Function to copy from the skel directory to the destination directory'''
    for destination in destination_paths:
        destination = expand_path(destination)
        if not exists(destination):  # Only copy if destination doesn't exist
            print(f"Copying from {skel_source} to {destination}")
            copytree(expand_path(skel_source), destination)
            break  # Copy to the first valid destination and stop

def main():
    # Setup argparse to handle command-line arguments
    parser = ArgumentParser(description="Setup configuration from skel to user directory.")
    parser.add_argument('config_name', type=str, help="Name of the configuration to setup (e.g., 'emacs').")
    args = parser.parse_args()

    config_name = args.config_name

    # Check if the given config_name is valid
    if config_name not in config_dict:
        print(f"Invalid configuration name '{config_name}'. Please provide a valid name.")
        print(f"Valid options are: {', '.join(config_dict.keys())}")
        sys.exit(1)  # Exit with a non-zero status indicating failure

    # Get the skel source and destination paths for the given config
    skel_source = config_dict[config_name][0][0]  # The first skel directory
    destination_paths = config_dict[config_name][1]  # The list of directories to check

    # Check if the configuration already exists in any of the paths
    existing_path = config_exists(destination_paths)
    if not existing_path:
        print(f"Configuration for {config_name} not found. Copying from skel...")
        copy_from_skel(skel_source, destination_paths)
    else:
        print(f"Configuration for {config_name} already exists in: {existing_path}")

if __name__ == "__main__":
    main()
