package com.honey.honey.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Loads configuration from a mounted secret file (tmpfs) with fallback to environment variables.
 * This allows switching between Railway (env vars) and Inferno (mounted file) deployments.
 * 
 * Priority:
 * 1. Mounted file at /run/secrets/honey-config.properties (Inferno)
 * 2. Environment variables (Railway)
 */
@Slf4j
public class ConfigLoader implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    private static final String SECRET_FILE_PATH = "/run/secrets/honey-config.properties";

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();

        Map<String, Object> configProperties = new HashMap<>();

        // Try to load from mounted file first (Inferno deployment)
        File secretFile = new File(SECRET_FILE_PATH);
        if (secretFile.exists() && secretFile.isFile() && secretFile.canRead()) {
            log.info("📁 Loading configuration from mounted secret file: {}", SECRET_FILE_PATH);
            try {
                Properties props = new Properties();
                try (FileInputStream fis = new FileInputStream(secretFile)) {
                    props.load(fis);
                }
                
                for (String key : props.stringPropertyNames()) {
                    String value = props.getProperty(key);
                    configProperties.put(key, value);
                    log.debug("Loaded from file: {} = {}", key, maskSensitiveValue(key, value));
                }
                log.info("✅ Successfully loaded {} properties from secret file", configProperties.size());
            } catch (IOException e) {
                log.warn("⚠️ Failed to read secret file, falling back to environment variables: {}", e.getMessage());
            }
        } else {
            log.info("📝 Secret file not found at {}, using environment variables", SECRET_FILE_PATH);
        }

        // Environment variables are already loaded by Spring Boot by default
        // We just add file-based config as a higher priority source if it exists
        if (!configProperties.isEmpty()) {
            propertySources.addFirst(new MapPropertySource("secretFileConfig", configProperties));
            log.info("✅ Configuration loaded: {} properties from file, environment variables as fallback", 
                    configProperties.size());
        } else {
            log.info("✅ Using environment variables for configuration");
        }
    }

    private String maskSensitiveValue(String key, String value) {
        if (value == null) return "null";
        if (key.toLowerCase().contains("password") || 
            key.toLowerCase().contains("token") || 
            key.toLowerCase().contains("secret") ||
            key.toLowerCase().contains("key")) {
            return value.length() > 4 ? value.substring(0, 2) + "***" + value.substring(value.length() - 2) : "***";
        }
        return value;
    }
}

