import os
import json
from pathlib import Path

# Default config path
CONFIG_DIR = os.path.expanduser("~/.config/bibtex-manager")
CONFIG_FILE = os.path.join(CONFIG_DIR, "config.json")

DEFAULT_CONFIG = {
    "dark_mode": True,
    "primary_color": "#11c8ff",
    "columns": {
        "ID": 25,
        "Type": 12,
        "Title": 50,
        "Author": 30,
        "Journal": 30,
        "Year": 10
    }
}

def load_config() -> dict:
    if not os.path.exists(CONFIG_FILE):
        return DEFAULT_CONFIG.copy()
    try:
        with open(CONFIG_FILE, 'r') as f:
            user_config = json.load(f)
            # Merge with default to ensure no missing keys
            config = DEFAULT_CONFIG.copy()
            
            # Update root keys
            if "dark_mode" in user_config:
                config["dark_mode"] = user_config["dark_mode"]
            if "primary_color" in user_config:
                config["primary_color"] = user_config["primary_color"]
                
            # Update column widths
            if "columns" in user_config:
                for col, width in user_config["columns"].items():
                    if col in config["columns"]:
                        config["columns"][col] = width
            return config
            
    except Exception:
        return DEFAULT_CONFIG.copy()

def save_config(config: dict) -> None:
    os.makedirs(CONFIG_DIR, exist_ok=True)
    with open(CONFIG_FILE, 'w') as f:
        json.dump(config, f, indent=4)
