# markdownconverter/utils/config.py

import json
import os

CONFIG_FILE = os.path.join(os.path.expanduser("~"), ".markdown_converter_config.json")

def save_configuration(last_markdown, last_template, add_toc, metadata):
    """
    Saves the entire GUI state to a JSON config file.
    """
    config_data = {
        "last_markdown_file": last_markdown,
        "last_template_file": last_template,
        "add_toc": add_toc,
        "metadata": metadata
    }
    try:
        with open(CONFIG_FILE, "w", encoding="utf-8") as f:
            json.dump(config_data, f, indent=4)
    except IOError as e:
        print(f"Error saving configuration: {e}")

def load_configuration():
    """
    Loads the entire GUI state from the JSON config file.
    """
    # --- CORREZIONE: Aggiorna le chiavi per i nuovi segnaposto ---
    defaults = {
        "last_markdown_file": "",
        "last_template_file": "",
        "add_toc": True,
        "metadata": {
            "DOC_SECURITY": "",
            "DOC_NUMBER": "",
            "DOC_REV": "",
            "DOC_PROJECT": "",
            "DOC_CUSTOMER": ""
        }
    }

    if not os.path.exists(CONFIG_FILE):
        return defaults

    try:
        with open(CONFIG_FILE, "r", encoding="utf-8") as f:
            loaded_config = json.load(f)
            # Make loading robust against older config files
            for key, value in defaults.items():
                if key not in loaded_config:
                    loaded_config[key] = value
                elif isinstance(value, dict):
                    for sub_key, sub_value in value.items():
                         if sub_key not in loaded_config.get(key, {}):
                             loaded_config[key][sub_key] = sub_value
            return loaded_config
            
    except (json.JSONDecodeError, IOError):
        return defaults