package de.winniepat.citrus.beta;

import de.winniepat.citrus.Client;
import net.minecraft.client.MinecraftClient;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;

public class HardwareIdentifier {
    private static HardwareIdentifier instance;
    private String hardwareId;

    private HardwareIdentifier() {
        this.hardwareId = generateHardwareId();
    }

    public static synchronized HardwareIdentifier getInstance() {
        if (instance == null) {
            instance = new HardwareIdentifier();
        }
        return instance;
    }

    private String generateHardwareId() {
        try {
            StringBuilder sb = new StringBuilder();

            sb.append(System.getProperty("os.name"));
            sb.append(System.getProperty("os.version"));
            sb.append(System.getProperty("os.arch"));
            sb.append(System.getProperty("user.name"));
            sb.append(System.getProperty("java.version"));
            sb.append(System.getProperty("user.country"));
            sb.append(Runtime.getRuntime().availableProcessors());

            try {
                if (MinecraftClient.getInstance() != null) {
                    String uuid = String.valueOf(MinecraftClient.getInstance().getSession().getUuidOrNull());
                    sb.append(uuid);
                }
            } catch (Exception e) {
                Client.logger.warn("Failed to generate hardware id", e);
            }

            String combined = sb.toString();
            String hash = Base64.getEncoder().encodeToString(
                    combined.getBytes(StandardCharsets.UTF_8)
            );

            return hash.substring(0, Math.min(32, hash.length()));

        } catch (Exception e) {
            Client.logger.warn("Failed to generate hardware ID, using UUID fallback", e);
            return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        }
    }

    public String getHardwareId() {
        return hardwareId;
    }
}