import java.util.*;
public class RetentionLab {
  record Cart(String id, int items) {}
  static final class Cache {
    final int max; final long ttl;
    final LinkedHashMap<String, Entry> entries = new LinkedHashMap<>(16,.75f,true);
    record Entry(Cart cart,long touched) {}
    Cache(int max,long ttl){if(max<1||ttl<1)throw new IllegalArgumentException();this.max=max;this.ttl=ttl;}
    synchronized Cart get(String id,long now,Map<String,Cart> store){
      entries.entrySet().removeIf(e->now-e.getValue().touched()>=ttl);
      Entry old=entries.get(id); Cart cart=old==null?store.get(id):old.cart();
      if(cart!=null){entries.put(id,new Entry(cart,now));while(entries.size()>max)entries.remove(entries.keySet().iterator().next());}
      return cart;
    }
    synchronized void invalidate(String id){entries.remove(id);}
  }
  public static void main(String[] args){
    Map<String,Cart> store=new HashMap<>(), unbounded=new HashMap<>(); Cache bounded=new Cache(100,20);
    for(int i=0;i<20000;i++){String id="cart-"+i; Cart c=new Cart(id,2);store.put(id,c);unbounded.put(id,c);bounded.get(id,0,store);}
    if(unbounded.size()!=20000||bounded.entries.size()!=100)throw new AssertionError("capacity");
    System.out.println("Unbounded entries: "+unbounded.size()+"; bounded entries: "+bounded.entries.size());
    if(bounded.get("cart-0",21,store)==null||bounded.entries.size()!=1)throw new AssertionError("expiry/reload");
    store.put("cart-0",new Cart("cart-0",3)); bounded.invalidate("cart-0");
    if(bounded.get("cart-0",22,store).items()!=3)throw new AssertionError("invalidation");
    Cache exact = new Cache(2,20);
    exact.get("cart-0",0,store);
    store.put("cart-0",new Cart("cart-0",4));
    if(exact.get("cart-0",20,store).items()!=4||exact.entries.get("cart-0").touched()!=20)throw new AssertionError("exact TTL reload");
    for(int i=0;i<20;i++)unbounded.put("same-key",new Cart("same-key",i));
    if(unbounded.size()!=20001)throw new AssertionError("same key cardinality");
    if(exact.get("missing",21,store)!=null)throw new AssertionError("invented empty cart");
    System.out.println("PASS: expiry, durable reload and invalidation (mock store; no heap benchmark)");
    System.out.println("PASS: exact TTL, repeated-key cardinality and missing-cart handling");
  }
}
