/*
MIT License

Copyright (c) <2025> <Paul Uszak>

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the 
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to 
permit persons to whom the Software is furnished to do so, subject to 
the following conditions:

The above copyright notice and this permission notice shall be included 
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

package com.reallyreallyrandom.isitrandom;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.compress.compressors.lzma.LZMACompressorOutputStream;

/*
isitrandom is statistically tied to commons-compress-1.27.0 and 
xz-1.9 libraries.  You must not change these libraries as that 
might invalidate the satistical simulation that it is based upon.
*/

public class Evaluate {

    // These are from the calibration notebook.
    private final static double K = 1.0136816356479579;
    private final static double A = 0.9999939265772589;

    public static void main(String[] args) {
        var test = new Evaluate();
        test.performTest(args);
    }

    private void performTest(String[] args) {
        try {
            // Create Options object
            Options options = new Options();

            // Add "help" option
            Option help = new Option("h", "help", false, "Show this help.");
            options.addOption(help);

            // Create a parser
            CommandLineParser parser = new DefaultParser();
            HelpFormatter formatter = new HelpFormatter();

            // Parse the command line arguments
            CommandLine cmd = parser.parse(options, args);

            // Check if "help" option is present
            if (cmd.hasOption("h")) {
                formatter.printHelp("java -jar  isitrandom_0.1.0.jar", options);
                System.exit(0);
            }

            // Get the first non-option argument as the filename
            String filename = null;
            String[] remainingArgs = cmd.getArgs();
            if (remainingArgs.length > 0) {
                filename = remainingArgs[0];
            } else {
                System.out.println("No filename provided.");
                System.exit(1);
            }

            System.out.println();
            System.out.println("Processing file: " + filename);
            System.out.println();
            var samples = Files.readAllBytes(Paths.get(filename));

            var samplesSize = samples.length;
            System.out.printf("Original file size: %,d %n", samplesSize);
            var testStatistic = compress(samples);
            System.out.printf("File compressed to: %,d %n", testStatistic);
            var criticalValue = Math.round(K * Math.pow(samplesSize, A));
            System.out.printf("Critical value is:  %,d %n", criticalValue);
            System.out.println();

            if (testStatistic >= criticalValue) {
                System.out.println("The file seems random with p > 0.05. But do further testing.");
            } else {
                System.out.println("The file doesn't seem random with p < 0.05.");
            }

            System.exit(0);
        } catch (Exception e) {
            System.err.println("There was a problem during testing...");
            System.out.println(e.toString());
            System.exit(1);
        }
    }

    private int compress(byte[] samples) throws IOException {
        int testStatistic;
        var bufferSize = (int) (samples.length * 1.3); // Allow 30% headroom.
        var baos = new ByteArrayOutputStream(bufferSize);
        try (var lzmaOut = new LZMACompressorOutputStream(baos)) {
            lzmaOut.write(samples);
            lzmaOut.flush();
            lzmaOut.close();

            testStatistic = baos.toByteArray().length;
        }
        return testStatistic;
    }
}
