# src/automation11/config.py

from pathlib import Path
import json
import importlib.resources as resources

APP_DIR = Path.cwd() / "11automation"
CONFIG_FILE = APP_DIR / "config.json"


def ensure_config_exists(**kwargs):
    APP_DIR.mkdir(exist_ok=True)

    if CONFIG_FILE.exists():
        with open(CONFIG_FILE, "r", encoding="utf-8") as f:
            config = json.load(f)
    else:
        with resources.files("automation11").joinpath(
            "default_config.json"
        ).open("r", encoding="utf-8") as f:
            config = json.load(f)

    # Update only fields provided by user
    for key, value in kwargs.items():
        if value is not None:
            config[key] = value

    with open(CONFIG_FILE, "w", encoding="utf-8") as f:
        json.dump(config, f, indent=2)

    return CONFIG_FILE


def load_config():
    if not CONFIG_FILE.exists():
        ensure_config_exists()

    with open(CONFIG_FILE, "r", encoding="utf-8") as f:
        return json.load(f)