package p162;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import net.jqwik.api.*;
import net.jqwik.api.lifecycle.AfterContainer;
import p162.GroundTruth;

public class TestCaseGenerator {

    static class TestCase {
        Map<String, Object> Inputs;
        Object Expected;
        TestCase(Map<String, Object> inputs, Object expected) {
            this.Inputs = inputs;
            this.Expected = expected;
        }
    }

    static List<TestCase> generatedCases = new ArrayList<>();
    static AtomicInteger caseCount = new AtomicInteger(0);
    static final int MAX_CASES = 500;

    @Property(tries = 10000)
    void generateTestCases(@ForAll("doubleValue") double p1, @ForAll("doubleValue") double p2,
                           @ForAll("doubleValue") double a1, @ForAll("doubleValue") double a2,
                           @ForAll("doubleValue") double b1, @ForAll("doubleValue") double b2) {
        if (caseCount.get() >= MAX_CASES) {
            return;
        }

        double result;
        try {
            result = GroundTruth.offset(p1, p2, a1, a2, b1, b2);
        } catch (Exception e) {
            return;
        }

        Map<String, Object> inputs = new LinkedHashMap<>();
        inputs.put("p1", p1);
        inputs.put("p2", p2);
        inputs.put("a1", a1);
        inputs.put("a2", a2);
        inputs.put("b1", b1);
        inputs.put("b2", b2);
        generatedCases.add(new TestCase(inputs, result));
        caseCount.incrementAndGet();
    }

    @Example
    void example1() {
        generateTestCases(0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
    }

    @Example
    void example2() {
        generateTestCases(1.0, 1.0, 1.0, 1.0, 1.0, 1.0);
    }

    @Example
    void example3() {
        generateTestCases(-1.0, -1.0, -1.0, -1.0, -1.0, -1.0);
    }

    @Example
    void example4() {
        generateTestCases(0.5, 0.5, 0.5, 0.5, 0.5, 0.5);
    }

    @Example
    void example5() {
        generateTestCases(0.0, 1.0, 1.0, 0.0, 1.0, 0.0);
    }

    @Provide
    Arbitrary<Double> doubleValue() {
        return Arbitraries.doubles().between(-1000.0, 1000.0);
    }

    @AfterContainer
    static void saveTestCases() throws IOException {
        if (generatedCases.isEmpty()) {
            return;
        }
        String dirPath = "src/test/java/test_cases";
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String filePath = dirPath + "/test_cases.json";
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        try (Writer writer = new FileWriter(filePath)) {
            gson.toJson(generatedCases, writer);
        }
        System.out.println("✅ Saved " + generatedCases.size() + " test cases to " + filePath);
    }
}