package com.cameleer.server.app.config;

import com.cameleer.server.core.license.LicenseGate;
import com.cameleer.server.core.license.LicenseInfo;
import com.cameleer.server.core.license.LicenseValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.file.Files;
import java.nio.file.Path;

@Configuration
public class LicenseBeanConfig {

    private static final Logger log = LoggerFactory.getLogger(LicenseBeanConfig.class);

    @Value("${cameleer.server.license.token:}")
    private String licenseToken;

    @Value("${cameleer.server.license.file:}")
    private String licenseFile;

    @Value("${cameleer.server.license.publickey:}")
    private String licensePublicKey;

    @Bean
    public LicenseGate licenseGate() {
        LicenseGate gate = new LicenseGate();

        String token = resolveLicenseToken();
        if (token == null || token.isBlank()) {
            log.info("No license configured — running in open mode (all features enabled)");
            return gate;
        }

        if (licensePublicKey == null || licensePublicKey.isBlank()) {
            log.warn("License token provided but no public key configured (CAMELEER_SERVER_LICENSE_PUBLICKEY). Running in open mode.");
            return gate;
        }

        try {
            LicenseValidator validator = new LicenseValidator(licensePublicKey);
            LicenseInfo info = validator.validate(token);
            gate.load(info);
        } catch (Exception e) {
            log.error("Failed to validate license: {}. Running in open mode.", e.getMessage());
        }

        return gate;
    }

    private String resolveLicenseToken() {
        if (licenseToken != null && !licenseToken.isBlank()) {
            return licenseToken;
        }
        if (licenseFile != null && !licenseFile.isBlank()) {
            try {
                return Files.readString(Path.of(licenseFile)).trim();
            } catch (Exception e) {
                log.warn("Failed to read license file {}: {}", licenseFile, e.getMessage());
            }
        }
        return null;
    }
}
