"""
File utility functions for the Excel Filter Tool
"""

import tkinter as tk
from tkinter import filedialog
import json
import logging

# Logging konfigurieren
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def browse_file(initialdir=None, filetypes=None, title="Datei auswählen"):
    """
    Opens a file dialog to browse and select a file
    
    Args:
        initialdir: Initial directory to open
        filetypes: File types to filter by
        title: Dialog title
        
    Returns:
        Selected file path or None if canceled
    """
    root = tk.Tk()
    root.withdraw()  # Hide the main window
    
    file_path = filedialog.askopenfilename(
        initialdir=initialdir,
        title=title,
        filetypes=filetypes
    )
    
    root.destroy()
    return file_path


def browse_save_file(initialdir=None, filetypes=None, title="Datei speichern", defaultextension=".xlsx"):
    """
    Opens a file dialog to browse and save a file
    
    Args:
        initialdir: Initial directory to open
        filetypes: File types to filter by
        title: Dialog title
        defaultextension: Default file extension
        
    Returns:
        Selected file path or None if canceled
    """
    root = tk.Tk()
    root.withdraw()  # Hide the main window
    
    file_path = filedialog.asksaveasfilename(
        initialdir=initialdir,
        title=title,
        filetypes=filetypes,
        defaultextension=defaultextension
    )
    
    root.destroy()
    return file_path


def load_config(config_file: str) -> dict:
    """
    Loads configuration from a JSON file
    
    Args:
        config_file: Path to the configuration file
        
    Returns:
        Dictionary containing the configuration
        
    Raises:
        Exception if the file cannot be loaded
    """
    try:
        with open(config_file, 'r') as f:
            config = json.load(f)
        logger.info(f"Configuration loaded: {config_file}")
        return config
    except FileNotFoundError:
        logger.warning(f"Configuration file not found: {config_file}")
        return {}
    except Exception as e:
        logger.error(f"Error loading configuration: {e}")
        raise Exception(f"Error loading configuration: {e}")


def save_config(config_file: str, config: dict):
    """
    Saves configuration to a JSON file
    
    Args:
        config_file: Path to the configuration file
        config: Dictionary containing the configuration to save
        
    Raises:
        Exception if the file cannot be saved
    """
    try:
        with open(config_file, 'w') as f:
            json.dump(config, f, indent=4)
        logger.info(f"Configuration saved: {config_file}")
    except Exception as e:
        logger.error(f"Error saving configuration: {e}")
        raise Exception(f"Error saving configuration: {e}")