import os, yaml
from pathlib import Path
from rich.console import Console
# Config helpers
# defining the path to the config file: ~/.jazari/config.yaml
CONFIG_DIR = os.path.join(Path.home(), '.jazari')
CONFIG_FILE = os.path.join(CONFIG_DIR, 'config.yaml')
console = Console()

def load_config():
    '''
    Loading config file if exists, otherwise returns empty dict.
    '''
    if os.path.exists(CONFIG_FILE):
        try:
            with open(CONFIG_FILE, 'r') as f:
                return yaml.safe_load(f) or {}
        except Exception as e:
            console.print(f'[yellow]Warning: Could not read config file: {e}[/yellow]')
    
    return {}

def get_config_default(key, CONFIG, default_value):
    '''
    Helper to get a default value from config or fall back to a hardcoded one.
    '''
    return CONFIG.get(key, default_value)

def make_config_dir(new_config):
    # Creating directory if doesn't exist
    Path(CONFIG_DIR).mkdir(parents = True, exist_ok=True)

    # Writing config to the yaml file
    with open(CONFIG_FILE, 'w') as f:
        yaml.dump(new_config, f, default_flow_style=False)
    
    console.print(f'\n[bold green]✅ Configuration saved![/bold green]')
    console.print('You can now run jobs without specifying these flags.')