package interview;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;

/** Dependency-free test runner: run with ./run-tests.sh (javac + java only). */
public final class AllTests {
    private static int passed, failed;

    public static void main(String[] args) throws Exception {
        test("LRU evicts least recently used", () -> {
            LruCache<String, Integer> c = new LruCache<>(2);
            c.put("a", 1); c.put("b", 2);
            check(c.get("a") == 1, "get a");
            c.put("c", 3); // evicts b
            check(c.get("b") == null, "b evicted");
            check(c.get("c") == 3 && c.size() == 2, "c present");
            c.put("a", 10);
            check(c.get("a") == 10, "update keeps key");
        });
        test("bounded buffer passes all items in order", () -> {
            BoundedBuffer<Integer> buf = new BoundedBuffer<>(2);
            AtomicInteger sum = new AtomicInteger();
            Thread consumer = Thread.ofPlatform().start(() -> {
                try { for (int i = 0; i < 100; i++) sum.addAndGet(buf.take()); }
                catch (InterruptedException e) { Thread.currentThread().interrupt(); }
            });
            for (int i = 1; i <= 100; i++) buf.put(i);
            consumer.join(5000);
            check(sum.get() == 5050, "sum " + sum.get());
        });
        test("singletons return one instance", () -> {
            check(Singletons.Config.getInstance() == Singletons.Config.getInstance(), "holder");
            check(Singletons.Connection.getInstance() == Singletons.Connection.getInstance(), "dcl");
            check(Singletons.Registry.INSTANCE.next() + 1 == Singletons.Registry.INSTANCE.next(), "enum");
        });
        test("sealed shapes and pattern matching", () -> {
            check(Math.abs(Shapes.area(new Shapes.Circle(1)) - Math.PI) < 1e-9, "circle");
            check(Shapes.area(new Shapes.Rectangle(2, 3)) == 6, "rect");
            check(Shapes.area(new Shapes.Square(4)) == 16, "square");
            check(new Shapes.Square(2).equals(new Shapes.Square(2)), "record equals");
            expectThrows(() -> new Shapes.Circle(-1), IllegalArgumentException.class);
        });
        test("string problems", () -> {
            check(Strings.reverse("java").equals("avaj"), "reverse");
            check(Strings.isPalindrome("A man, a plan, a canal: Panama"), "palindrome");
            check(!Strings.isPalindrome("race a car"), "not palindrome");
            check(Strings.isAnagram("listen", "silent") && !Strings.isAnagram("ab", "aa"), "anagram");
            check(Strings.firstNonRepeated("swiss").equals(Optional.of('w')), "first non-repeated");
            check(Strings.firstNonRepeated("aabb").isEmpty(), "none");
            check(Strings.frequencies("aab").equals(Map.of('a', 2L, 'b', 1L)), "freq");
        });
        test("equals and hashCode contract", () -> {
            Money a = new Money(150, "USD"), b = new Money(150, "USD");
            check(a.equals(b) && a.hashCode() == b.hashCode(), "equal objects, equal hashes");
            check(new java.util.HashSet<>(List.of(a, b)).size() == 1, "set dedupes");
            check(a.plus(b).toString().equals("USD 3.00"), "plus");
            expectThrows(() -> a.plus(new Money(1, "EUR")), IllegalArgumentException.class);
        });
        test("concurrency", () -> {
            check(Concurrency.parallelCount(8, 10_000) == 80_000, "no lost updates");
            List<Integer> sq = Concurrency.squaresOnVirtualThreads(1000);
            check(sq.size() == 1000 && sq.get(9) == 100, "virtual threads");
            List<String> oe = Concurrency.oddEven(6);
            check(oe.equals(List.of("odd:1", "even:2", "odd:3", "even:4", "odd:5", "even:6")), "odd/even " + oe);
        });
        test("streams", () -> {
            var es = List.of(
                    new Streams.Employee("Ana", "eng", 120), new Streams.Employee("Bo", "eng", 100),
                    new Streams.Employee("Cy", "ops", 90), new Streams.Employee("Di", "ops", 120));
            check(Streams.averageSalaryByDept(es).get("eng") == 110.0, "avg");
            check(Streams.secondHighestSalary(es).equals(Optional.of(100.0)), "second highest");
            check(Streams.topEarnerByDept(es).get("ops").get().name().equals("Di"), "top");
            check(Streams.partitionBySalary(es, 110).get(true).equals(List.of("Ana", "Di")), "partition");
            check(Streams.namesJoined(es).equals("[Ana, Bo, Cy, Di]"), "join");
        });

        System.out.printf("%d passed, %d failed%n", passed, failed);
        if (failed > 0) System.exit(1);
    }

    interface Body { void run() throws Exception; }

    private static void test(String name, Body body) {
        try {
            body.run();
            passed++;
            System.out.println("ok   " + name);
        } catch (Throwable t) {
            failed++;
            System.out.println("FAIL " + name + ": " + t);
        }
    }

    private static void check(boolean cond, String what) {
        if (!cond) throw new AssertionError(what);
    }

    private static void expectThrows(Body body, Class<? extends Throwable> type) throws Exception {
        try {
            body.run();
        } catch (Throwable t) {
            if (type.isInstance(t)) return;
            throw new AssertionError("expected " + type.getSimpleName() + " but got " + t);
        }
        throw new AssertionError("expected " + type.getSimpleName());
    }
}
