package gregtech.api.util;

import java.util.Locale;
import java.util.Random;

/**
 * Reference generator: drives the unmodified 2.9.0 OverclockCalculator.java and a copy of the numeric path of
 * ParallelHelper.determineParallel (ParallelHelper.java:375-534, items/fluids replaced by an input limit) and
 * ProcessingLogic.applyRecipe (ProcessingLogic.java:484-517). Prints one JSON object per line.
 */
public class RefMain {

    static final long[] V = GTUtility.V;
    static final double MAX_BATCH_MODE_TICK_TIME = 128; // ParallelHelper.java:25

    static String d(double x) {
        if (Double.isNaN(x)) return "\"NaN\"";
        if (Double.isInfinite(x)) return x > 0 ? "\"Infinity\"" : "\"-Infinity\"";
        return Double.toString(x);
    }

    static <T> T pick(Random r, T[] a) {
        return a[r.nextInt(a.length)];
    }

    static long pickL(Random r, long[] a) {
        return a[r.nextInt(a.length)];
    }

    static double pickD(Random r, double[] a) {
        return a[r.nextInt(a.length)];
    }

    static int pickI(Random r, int[] a) {
        return a[r.nextInt(a.length)];
    }

    static final class Case {

        long recipeEUt;
        int duration;
        long voltage, amperage;
        int maxParallel;
        double euMod = 1, speed = 1;
        double timeRed = 2, powerInc = 4;
        boolean amperageOC = true, laserOC;
        int maxTierSkips = 1;
        int maxOC = Integer.MAX_VALUE, maxRegOC = Integer.MAX_VALUE;
        int recipeHeat, machineHeat;
        boolean heatOC, heatDiscount;
        int batch = 1;
        int inputLimit = Integer.MAX_VALUE;
        double underOneTick = -1; // < 0: none

        OverclockCalculator calc() {
            OverclockCalculator c = new OverclockCalculator().setRecipeEUt(recipeEUt)
                .setAmperage(amperage)
                .setEUt(voltage)
                .setMaxTierSkips(maxTierSkips)
                .setDuration(duration)
                .setDurationModifier(speed)
                .setEUtDiscount(euMod)
                .setAmperageOC(amperageOC)
                .setDurationDecreasePerOC(timeRed)
                .setEUtIncreasePerOC(powerInc)
                .setLaserOC(laserOC)
                .setMaxOverclocks(maxOC)
                .setMaxRegularOverclocks(maxRegOC)
                .setRecipeHeat(recipeHeat)
                .setMachineHeat(machineHeat)
                .setHeatOC(heatOC)
                .setHeatDiscount(heatDiscount);
            if (underOneTick >= 0) {
                final double u = underOneTick;
                c.setDurationUnderOneTickSupplier(() -> u);
            }
            return c;
        }

        String inputsJson() {
            return String.format(
                Locale.ROOT,
                "\"recipeEUt\":%d,\"duration\":%d,\"voltage\":%d,\"amperage\":%d,\"maxParallel\":%d,\"euMod\":%s,\"speed\":%s,"
                    + "\"timeRed\":%s,\"powerInc\":%s,\"amperageOC\":%b,\"laserOC\":%b,\"maxTierSkips\":%d,\"maxOC\":%d,\"maxRegOC\":%d,"
                    + "\"recipeHeat\":%d,\"machineHeat\":%d,\"heatOC\":%b,\"heatDiscount\":%b,\"batch\":%d,\"inputLimit\":%d,\"underOneTick\":%s",
                recipeEUt, duration, voltage, amperage, maxParallel, d(euMod), d(speed), d(timeRed), d(powerInc), amperageOC,
                laserOC, maxTierSkips, maxOC, maxRegOC, recipeHeat, machineHeat, heatOC, heatDiscount, batch, inputLimit,
                d(underOneTick));
        }
    }

    // Copy of the numeric path of ParallelHelper.determineParallel + ProcessingLogic.applyRecipe.
    static String process(Case k) {
        OverclockCalculator calculator = k.calc();
        long availableEUt = k.voltage * k.amperage;
        int maxParallel = k.maxParallel;
        boolean batchMode = k.batch > 1;
        int batchModifier = k.batch;
        double eutModifier = k.euMod;
        if (maxParallel <= 0) return "\"result\":\"NONE\"";

        double heatDiscountMultiplier = calculator.calculateHeatDiscountMultiplier();
        final long tRecipeEUt = (long) Math.ceil(k.recipeEUt * eutModifier * heatDiscountMultiplier);
        if (availableEUt < tRecipeEUt) return "\"result\":\"INSUFFICIENT_POWER\",\"value\":" + tRecipeEUt;
        if (k.recipeEUt > calculator.getMaxAllowedRecipeEUt())
            return "\"result\":\"INSUFFICIENT_VOLTAGE\",\"value\":" + k.recipeEUt;

        int originalMaxParallel = maxParallel;
        calculator.setParallel(originalMaxParallel);
        double sub = -1;
        if (calculator.hasDurationUnderOneTickSupplier()) {
            if (calculator.getDurationUnderOneTickSupplier() < 1) {
                maxParallel = GTUtility.safeInt((long) (maxParallel / calculator.getDurationUnderOneTickSupplier()), 0);
            }
        } else {
            sub = calculator.calculateMultiplierUnderOneTick();
            maxParallel = GTUtility.safeInt((long) (maxParallel * sub), 0);
        }
        int maxParallelBeforeBatchMode = maxParallel;
        if (batchMode) {
            maxParallel = GTUtility.safeInt((long) maxParallel * batchModifier, 0);
        }
        maxParallelBeforeBatchMode = Math.min(maxParallel, maxParallelBeforeBatchMode);
        int actualMaxParallel = tRecipeEUt > 0 ? (int) Math.min(maxParallelBeforeBatchMode, availableEUt / tRecipeEUt)
            : maxParallelBeforeBatchMode;
        int currentParallel = Math.min(actualMaxParallel, k.inputLimit);
        if (currentParallel <= 0) return "\"result\":\"INTERNAL_ERROR\"";
        calculator.setCurrentParallel(currentParallel)
            .calculate();
        double durationMultiplier = 0;
        if (batchMode && currentParallel > 0 && calculator.getDuration() < MAX_BATCH_MODE_TICK_TIME) {
            int tExtraParallels;
            double batchMultiplierMax = MAX_BATCH_MODE_TICK_TIME / calculator.getDuration();
            final int maxExtraParallels = (int) Math.floor(
                Math.min(
                    currentParallel * Math.min(batchMultiplierMax - 1, batchModifier - 1),
                    maxParallel - currentParallel));
            tExtraParallels = Math.max(0, Math.min(maxExtraParallels, k.inputLimit - currentParallel));
            durationMultiplier = 1.0f + (float) tExtraParallels / currentParallel;
            currentParallel += tExtraParallels;
        }
        double dm = batchMode && durationMultiplier > 0 ? durationMultiplier : 1;
        if (calculator.getConsumption() == Long.MAX_VALUE) return "\"result\":\"POWER_OVERFLOW\"";
        if (calculator.getDuration() == Integer.MAX_VALUE) return "\"result\":\"DURATION_OVERFLOW\"";
        double finalDuration = calculator.getDuration() * dm;
        if (finalDuration >= Integer.MAX_VALUE) return "\"result\":\"DURATION_OVERFLOW\"";
        return String.format(
            Locale.ROOT,
            "\"result\":\"SUCCESSFUL\",\"parallel\":%d,\"eut\":%d,\"duration\":%d,\"overclocks\":%d,\"sub\":%s,\"durationMultiplier\":%s",
            currentParallel, calculator.getConsumption(), (int) finalDuration, calculator.getPerformedOverclocks(), d(sub),
            d(dm));
    }

    // Plain OverclockCalculator: calculate() with parallel 1 and the multiplier on a fresh instance.
    static String plain(Case k) {
        OverclockCalculator c1 = k.calc();
        double mult = c1.calculateMultiplierUnderOneTick();
        OverclockCalculator c2 = k.calc();
        c2.calculate();
        return String.format(
            Locale.ROOT,
            "\"eut\":%d,\"duration\":%d,\"overclocks\":%d,\"mult\":%s",
            c2.getConsumption(), c2.getDuration(), c2.getPerformedOverclocks(), d(mult));
    }

    // Single case from key=value arguments, e.g. `case recipeEUt=1920 duration=2500 voltage=8192 amperage=4 heatOC=true`.
    static void single(String[] args) {
        Case k = new Case();
        k.maxParallel = 1;
        k.voltage = 32;
        k.amperage = 1;
        for (int i = 1; i < args.length; i++) {
            String[] kv = args[i].split("=", 2);
            String v = kv[1];
            switch (kv[0]) {
                case "recipeEUt" -> k.recipeEUt = Long.parseLong(v);
                case "duration" -> k.duration = Integer.parseInt(v);
                case "voltage" -> k.voltage = Long.parseLong(v);
                case "amperage" -> k.amperage = Long.parseLong(v);
                case "maxParallel" -> k.maxParallel = Integer.parseInt(v);
                case "euMod" -> k.euMod = Double.parseDouble(v);
                case "speed" -> k.speed = Double.parseDouble(v);
                case "timeRed" -> k.timeRed = Double.parseDouble(v);
                case "powerInc" -> k.powerInc = Double.parseDouble(v);
                case "amperageOC" -> k.amperageOC = Boolean.parseBoolean(v);
                case "laserOC" -> k.laserOC = Boolean.parseBoolean(v);
                case "maxTierSkips" -> k.maxTierSkips = Integer.parseInt(v);
                case "maxOC" -> k.maxOC = Integer.parseInt(v);
                case "maxRegOC" -> k.maxRegOC = Integer.parseInt(v);
                case "recipeHeat" -> k.recipeHeat = Integer.parseInt(v);
                case "machineHeat" -> k.machineHeat = Integer.parseInt(v);
                case "heatOC" -> k.heatOC = Boolean.parseBoolean(v);
                case "heatDiscount" -> k.heatDiscount = Boolean.parseBoolean(v);
                case "batch" -> k.batch = Integer.parseInt(v);
                case "inputLimit" -> k.inputLimit = Integer.parseInt(v);
                case "underOneTick" -> k.underOneTick = Double.parseDouble(v);
                default -> throw new IllegalArgumentException("unknown key " + kv[0]);
            }
        }
        System.out.println("{" + k.inputsJson() + ",\"plain\":{" + plain(k) + "},\"process\":{" + process(k) + "}}");
    }

    public static void main(String[] args) {
        if (args.length > 0 && args[0].equals("case")) {
            single(args);
            return;
        }
        int n = args.length > 0 ? Integer.parseInt(args[0]) : 3000;
        Random r = new Random(290);
        long[] specialEUt = { 1, 7, 8, 16, 30, 31, 32, 33, 120, 128, 480, 512, 1920, 2048, 7680, 30720, 122880, 491520,
            1966080, 7864320, 31457280, 125829120, 503316480, 2013265912, 2147483640L, 23950, 98304 };
        int[] specialDur = { 1, 2, 3, 4, 5, 8, 16, 20, 37, 64, 100, 128, 200, 256, 400, 600, 960, 1200, 4000, 28800, 61035,
            100000 };
        long[] amps = { 1, 2, 3, 4, 8, 16, 64, 256, 1024, 4096, 65536, 1048576, 4194304 };
        double[] euMods = { 1, 1, 1, 0.9, 0.8, 0.75, 0.6, 0.5, (double) 0.8f, (double) 0.9f, Math.sqrt(2), 1.25 };
        double[] speeds = { 1, 1, 1, 0.5, 0.25, 1 / 3.5, 1 / 2.5, 0.4, (double) (1 / 2.2f), 0.2, 1.5, 0.1, 0.01 };
        int[] heats = { 0, 1800, 2700, 3600, 4500, 5400, 6300, 7200, 9000, 10800, 12600 };
        int[] coilHeats = { 1801, 2701, 3601, 4501, 5401, 6301, 7201, 8101, 9001, 9901, 10801, 11701, 12601, 13501 };
        for (int i = 0; i < n; i++) {
            Case k = new Case();
            k.recipeEUt = r.nextInt(3) == 0 ? 1 + r.nextInt(r.nextBoolean() ? 2000 : 4_000_000) : pickL(r, specialEUt);
            k.duration = r.nextInt(3) == 0 ? 1 + r.nextInt(r.nextBoolean() ? 50 : 20000) : pickI(r, specialDur);
            int vt = r.nextInt(15);
            k.voltage = r.nextInt(6) == 0 ? V[vt] + V[Math.max(0, vt - 1)] : V[vt]; // sometimes a non-tier average
            k.amperage = pickL(r, amps);
            k.maxParallel = r.nextInt(3) == 0 ? 1 : pickI(r, new int[] { 2, 4, 8, 16, 64, 256, 1024, 4096, 65536, 1 << 20 });
            k.euMod = pickD(r, euMods);
            k.speed = pickD(r, speeds);
            int ocMode = r.nextInt(6);
            if (ocMode == 1) k.timeRed = 4; // perfect
            if (ocMode == 2) {
                k.timeRed = 2;
                k.powerInc = 2;
            }
            if (ocMode == 3) {
                k.timeRed = 4;
                k.powerInc = 2;
            }
            k.amperageOC = r.nextInt(5) != 0;
            k.laserOC = r.nextInt(6) == 0;
            k.maxTierSkips = r.nextInt(4) == 0 ? Integer.MAX_VALUE : 1;
            if (r.nextInt(6) == 0) k.maxOC = r.nextInt(6);
            if (k.laserOC && r.nextInt(2) == 0) k.maxRegOC = r.nextInt(6);
            if (r.nextInt(3) == 0) {
                k.recipeHeat = pickI(r, heats);
                k.machineHeat = pickI(r, coilHeats) + 100 * (r.nextInt(14) - 2);
                k.heatOC = true;
                k.heatDiscount = true;
            }
            if (r.nextInt(4) == 0) k.batch = 128;
            if (r.nextInt(6) == 0) k.inputLimit = 1 + r.nextInt(5000);
            if (r.nextInt(25) == 0) k.underOneTick = pickD(r, new double[] { 0.05, 0.3, 0.5, 1, 2.5, 10 });
            System.out.println("{" + k.inputsJson() + ",\"plain\":{" + plain(k) + "},\"process\":{" + process(k) + "}}");
        }
    }
}
