package com.livingworld.config;

import com.livingworld.core.services.ConfigService;
import com.livingworld.debug.DiagnosticCategory;
import com.livingworld.debug.LivingWorldLogger;

/**
 * Default implementation of {@link ConfigService}.
 *
 * <p>Holds a single {@link SimulationConfig} instance. The constructor creates
 * a fresh default configuration and validates it immediately so that invalid
 * defaults are caught at startup rather than at runtime.</p>
 */
public class DefaultConfigService implements ConfigService {

    private SimulationConfig config;

    /**
     * Creates a new service with default simulation settings.
     *
     * @throws RuntimeException if the default configuration fails validation
     */
    public DefaultConfigService() {
        this.config = new SimulationConfig();
        validate(); // validates and logs success
    }

    @Override
    public SimulationConfig getSimulationConfig() {
        return config;
    }

    /**
     * Reloads configuration by creating a fresh default {@link SimulationConfig}
     * and revalidating it.
     */
    @Override
    public void reload() {
        this.config = new SimulationConfig();
        validate(); // validates and logs success
    }

    /**
     * Validates the current configuration by delegating to
     * {@link SimulationConfig#validate()}.  On success logs an informational
     * message via {@link LivingWorldLogger}.
     *
     * @throws RuntimeException if validation fails (wraps {@link IllegalArgumentException})
     */
    @Override
    public void validate() {
        try {
            config.validate();
            LivingWorldLogger.info(DiagnosticCategory.CONFIG, "Configuration validated successfully: " + config);
        } catch (IllegalArgumentException e) {
            LivingWorldLogger.error(DiagnosticCategory.CONFIG, "Configuration validation failed", e);
            throw new RuntimeException("Configuration validation failed", e);
        }
    }
}