package com.bsphp.login;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 本机特征码：优先 Mac IOPlatformUUID（ioreg），否则持久化随机 UUID（与 Mac 演示 fallback 行为类似）。
 */
public final class MachineCodeUtil {

    private static final String CACHE_FILE = ".bsphp-java-machine-code";

    private MachineCodeUtil() {}

    public static String getMachineCode() {
        String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT);
        if (os.contains("mac")) {
            String u = tryIoregPlatformUuid();
            if (u != null && !u.isEmpty()) {
                return u;
            }
        }
        return fallbackUuid();
    }

    private static String tryIoregPlatformUuid() {
        try {
            Process p = new ProcessBuilder(
                    "ioreg", "-rd1", "-c", "IOPlatformExpertDevice"
            ).redirectErrorStream(true).start();
            if (!p.waitFor(5, TimeUnit.SECONDS)) {
                p.destroyForcibly();
                return null;
            }
            try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = br.readLine()) != null) {
                    int idx = line.indexOf("\"IOPlatformUUID\"");
                    if (idx < 0) continue;
                    int q1 = line.indexOf('"', idx + 16);
                    if (q1 < 0) continue;
                    int q2 = line.indexOf('"', q1 + 1);
                    if (q2 > q1) {
                        return line.substring(q1 + 1, q2);
                    }
                }
            }
        } catch (Exception ignored) {
        }
        return null;
    }

    private static String fallbackUuid() {
        try {
            Path home = Path.of(System.getProperty("user.home", "."));
            Path f = home.resolve(CACHE_FILE);
            if (Files.isRegularFile(f)) {
                String s = Files.readString(f, StandardCharsets.UTF_8).trim();
                if (!s.isEmpty()) return s;
            }
            String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ROOT);
            Files.writeString(f, uuid, StandardCharsets.UTF_8);
            return uuid;
        } catch (Exception e) {
            return UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ROOT);
        }
    }
}
