/*
===============================================================================
DETERMINISTIC BLACKJACK DECISION ENGINE RESEARCH
PHASE 3.30 - AFFORDABILITY ENFORCEMENT CALIBRATION AT CONSTANT 5x

CODE VERSION: Deterministic Blackjack Phase 3.30
CODE BUILD TAG: DBDE-3.30-AFFORDABILITY-ENFORCEMENT-5X

RESEARCH DIRECTOR: Amit Amlani
PUBLICATION AUTHOR: ChatGPT (OpenAI)

PURPOSE
Phase 3.30 implements explicit affordability enforcement at constant 5x.

NO WAGER INCREASE.
The base wager remains 5 units.

DECISION POLICY
The Phase 3.20 policy remains the requested policy whenever it is financially
executable. Phase 3.30 adds a separate BANKROLL-AFFORDABILITY OVERRIDE only
when the requested commitment cannot be funded.

DETERMINISTIC AFFORDABILITY RULE
1. A new hand starts only when bankroll >= BASE_WAGER.
2. An initial SPLIT is executed only when bankroll can fund both 5-unit stakes.
3. Each DOUBLE is executed only when bankroll can fund the additional 5-unit
   commitment after all stakes already committed to that round.
4. If SPLIT is unaffordable, the original two-card hand remains unsplit.
5. If DOUBLE is unaffordable, use the textbook non-double fallback for that
   visible state; if textbook itself says DOUBLE, fallback is HIT.
6. If a base wager is unaffordable, the Selective session stops and its
   remaining bankroll is retained rather than inventing additional capital.

WHY THIS FALLBACK
It separates strategy from financing. We do not borrow imaginary money, and
we do not automatically force a risky HIT merely because a split was denied.
For an unaffordable DOUBLE, textbook play is the conservative deterministic
fallback, with DOUBLE converted to HIT when it too is unavailable.

CALIBRATION TARGET
Phase 3.29 observed 40 affordability conflicts in Primary and 46 in Holdout.
Phase 3.30 must remove all impossible commitments and quantify how the
resulting legal fallbacks change outcomes.

FROZEN CONTROLS
Six exact decks; deterministic session-start shuffle; 30-hand maximum horizon;
100-unit starting bankroll; constant 5-unit base wager; bankruptcy stop;
frozen Selective policy except explicit affordability override; S17; DAS;
one split; blackjack 3:2; no surrender; no in-session reshuffle; no card
counting, history, composition, hidden-card or future-card knowledge.
===============================================================================
*/
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.MessageDigest;
import java.util.*;

public final class DeterministicBlackjackPhase330 {
    static final int SESSIONS = 5000;
    static final int HANDS = 30;
    static final int SHOE_SIZE = 312;
    static final double START_BANK = 100.0;
    static final double BASE_WAGER = 5.0;
    static final long PRIMARY_SEED = 202001L;
    static final long HOLDOUT_SEED = 202101L;

    enum Action { HIT, STAND, DOUBLE, SPLIT, NONE }
    enum Profile { TEXTBOOK, MAXIMUM_AGGRESSION, SELECTIVE_AGGRESSION }

    static final class Hand {
        final ArrayList<Integer> c = new ArrayList<>();
        int total(){int t=0,a=0;for(int v:c){t+=v;if(v==11)a++;}while(t>21&&a-->0)t-=10;return t;}
        boolean soft(){int raw=0;for(int v:c)raw+=v;return c.contains(11)&&raw==total();}
        boolean bust(){return total()>21;}
        boolean blackjack(){return c.size()==2&&total()==21;}
        int cards(){return c.size();}
    }

    static final class ResolvedHandRecord {
        String cohort;
        int session, round, child;
        boolean splitChild;
        int startTotal;
        boolean startSoft;
        int dealerUp;
        String visibleClass;
        Action textbookAction;
        Action aggressiveAction;
        int startCards;
        int endCards;
        double stake;
        boolean thirdCardTaken;
        boolean thirdCardBust;
        boolean bust;
        String outcome;
        double net;
        int startPointer, endPointer;

        String csv(){
            return String.join(",",
                cohort,Integer.toString(session),Integer.toString(round),Integer.toString(child),Boolean.toString(splitChild),
                Integer.toString(startTotal),Boolean.toString(startSoft),Integer.toString(dealerUp),visibleClass,
                textbookAction.toString(),aggressiveAction.toString(),Integer.toString(startCards),Integer.toString(endCards),
                String.format(Locale.ROOT,"%.1f",stake),Boolean.toString(thirdCardTaken),Boolean.toString(thirdCardBust),
                Boolean.toString(bust),outcome,String.format(Locale.ROOT,"%.1f",net),Integer.toString(startPointer),Integer.toString(endPointer));
        }
    }

    static final class Round {
        double net;
        int endPointer;
        int doubles, splits;
        boolean win, loss, push;
        final ArrayList<ResolvedHandRecord> records = new ArrayList<>();
    }

    static final class PairStats {
        long sessions,tPositive,tNegative,tEven,aPositive,aNegative,aEven,tHigher,aHigher,tie;
        long t2x,t3x,t5x,t10x,a2x,a3x,a5x,a10x;
        double tEnd,aEnd;
        long tWins,tLosses,tPushes,aWins,aLosses,aPushes,tDoubles,aDoubles,tSplits,aSplits;
        long diverged,firstDivSum,sameStart,totalStarts,finalSame,tAhead,aAhead,absDiff,tCards,aCards;
        int maxT,maxA;
        double maxBankT=START_BANK,maxBankA=START_BANK;
        int maxBankTHand=0,maxBankAHand=0,maxBankTSession=0,maxBankASession=0;
        final double[] aBankAfterHand=new double[HANDS+1];
        double sumSessionPeakA,sumMaxDrawdownA;
        long aEver2x,aEver3x,aEver5x,aEver10x,aEverZero,aBankruptcyStops,aHandsSkippedAfterBankruptcy;
        long affordabilityBaseStops,affordabilitySplitFallbacks,affordabilityDoubleFallbacks;
        final long[] peakHandCountsA=new long[HANDS+1];
    }

    static final class StateKey implements Comparable<StateKey> {
        final int total, up;
        final boolean soft, splitChild;
        final Action textbook;
        StateKey(int total,boolean soft,int up,boolean splitChild,Action textbook){this.total=total;this.soft=soft;this.up=up;this.splitChild=splitChild;this.textbook=textbook;}
        public int compareTo(StateKey o){int c=Integer.compare(total,o.total);if(c!=0)return c;c=Boolean.compare(soft,o.soft);if(c!=0)return c;c=Integer.compare(up,o.up);if(c!=0)return c;c=Boolean.compare(splitChild,o.splitChild);if(c!=0)return c;return textbook.compareTo(o.textbook);}
        public boolean equals(Object x){if(!(x instanceof StateKey))return false;StateKey o=(StateKey)x;return total==o.total&&soft==o.soft&&up==o.up&&splitChild==o.splitChild&&textbook==o.textbook;}
        public int hashCode(){return Objects.hash(total,soft,up,splitChild,textbook);}
        String label(){return (soft?"SOFT ":"HARD ")+total+" vs "+up+(splitChild?" [split-child]":"")+" | textbook="+textbook;}
    }

    static final class StateAgg {
        long hands,wins,losses,pushes,busts,thirdTaken,thirdBust;
        double net,stake;
        void add(ResolvedHandRecord r){hands++;net+=r.net;stake+=r.stake;if(r.outcome.equals("WIN"))wins++;else if(r.outcome.equals("LOSS"))losses++;else pushes++;if(r.bust)busts++;if(r.thirdCardTaken)thirdTaken++;if(r.thirdCardBust)thirdBust++;}
    }

    static long sessionSeed(long cohort,int s){return cohort+s*1_000_003L;}

    static int[] sixDeckShoe(long seed){
        int[] a=new int[SHOE_SIZE];int p=0;
        for(int deck=0;deck<6;deck++)for(int suit=0;suit<4;suit++)for(int rank=1;rank<=13;rank++)a[p++]=rank==1?11:Math.min(rank,10);
        Random r=new Random(seed);
        for(int i=a.length-1;i>0;i--){int j=r.nextInt(i+1);int t=a[i];a[i]=a[j];a[j]=t;}
        return a;
    }

    static boolean auditShoe(int[] s){
        if(s.length!=312)return false;int ace=0,ten=0;int[] n=new int[10];
        for(int v:s){if(v==11)ace++;else if(v==10)ten++;else if(v>=2&&v<=9)n[v]++;else return false;}
        if(ace!=24||ten!=96)return false;for(int v=2;v<=9;v++)if(n[v]!=24)return false;return true;
    }

    static int draw(int[] shoe,int[] ptr){if(ptr[0]>=shoe.length)throw new IllegalStateException("Shoe exhausted at pointer "+ptr[0]);return shoe[ptr[0]++];}

    static Action textbook(Hand h,int up,boolean first){
        int t=h.total();
        if(h.soft()){
            if(t>=19)return Action.STAND;
            if(t==18)return first&&up>=3&&up<=6?Action.DOUBLE:(up>=9?Action.HIT:Action.STAND);
            if(t==17)return first&&up>=3&&up<=6?Action.DOUBLE:Action.HIT;
            if(t==15||t==16)return first&&up>=4&&up<=6?Action.DOUBLE:Action.HIT;
            if(t==13||t==14)return first&&up>=5&&up<=6?Action.DOUBLE:Action.HIT;
            return Action.HIT;
        }
        if(t>=17)return Action.STAND;
        if(t>=13)return up>=2&&up<=6?Action.STAND:Action.HIT;
        if(t==12)return up>=4&&up<=6?Action.STAND:Action.HIT;
        if(t==11)return first&&up!=11?Action.DOUBLE:Action.HIT;
        if(t==10)return first&&up<=9?Action.DOUBLE:Action.HIT;
        if(t==9)return first&&up>=3&&up<=6?Action.DOUBLE:Action.HIT;
        return Action.HIT;
    }

    static boolean textbookSplit(int pair,int up){
        if(pair==11||pair==8)return true;if(pair==10||pair==5)return false;
        if(pair==9)return up!=7&&up!=10&&up!=11;if(pair==7)return up>=2&&up<=7;
        if(pair==6)return up>=2&&up<=6;if(pair==4)return up==5||up==6;
        if(pair==3||pair==2)return up>=2&&up<=7;return false;
    }

    // Rank normalisation collapses 10/J/Q/K to value 10. Therefore K+J,
    // Q+10, J+K, etc. arrive here as 10+10 and are split-eligible.
    static boolean splitEligibleByStoredValue(int firstCard,int secondCard){
        return firstCard==secondCard;
    }

    static String tenValueSplitAudit(){
        int ten=10,jack=10,queen=10,king=10;
        int[][] cases={{ten,jack},{ten,queen},{ten,king},{jack,queen},{jack,king},{queen,king},{ten,ten},{jack,jack},{queen,queen},{king,king}};
        String[] names={"10+J","10+Q","10+K","J+Q","J+K","Q+K","10+10","J+J","Q+Q","K+K"};
        StringBuilder b=new StringBuilder("PHASE 3.02 — TEN-VALUE SPLIT PRECEDENCE AUDIT\n\n");
        b.append("Stored-card rule: 10, J, Q and K are all represented as integer value 10.\n");
        b.append("Maximum Aggression precedence: SPLIT eligible initial pair first; only otherwise consider first-decision DOUBLE.\n\n");
        for(int i=0;i<cases.length;i++){
            boolean ok=splitEligibleByStoredValue(cases[i][0],cases[i][1]);
            b.append(String.format(Locale.ROOT,"%-5s -> stored %d+%d -> split eligible = %s -> first aggressive action = %s%n",
                    names[i],cases[i][0],cases[i][1],ok,ok?"SPLIT":"DOUBLE-CANDIDATE"));
            if(!ok)throw new IllegalStateException("Ten-value split audit failed for "+names[i]);
        }
        b.append("\nRESULT: PASS — every two-card ten-value combination is routed to SPLIT before DOUBLE.\n");
        return b.toString();
    }

    static String visibleClass(Hand h){return h.soft()?"SOFT":"HARD";}

    static Round playRound(int[] shoe,int pointer,Profile profile,String cohort,int session,int round,boolean capture,double availableBank,PairStats stats){
        int[] ptr={pointer};Hand initial=new Hand(),dealer=new Hand();
        initial.c.add(draw(shoe,ptr));dealer.c.add(draw(shoe,ptr));initial.c.add(draw(shoe,ptr));dealer.c.add(draw(shoe,ptr));
        boolean pair=splitEligibleByStoredValue(initial.c.get(0),initial.c.get(1));
        boolean aggressive=profile==Profile.MAXIMUM_AGGRESSION||profile==Profile.SELECTIVE_AGGRESSION;
        boolean selective=profile==Profile.SELECTIVE_AGGRESSION;
        boolean wantsSplit=pair&&(aggressive||textbookSplit(initial.c.get(0),dealer.c.get(0)));
        if(capture && wantsSplit && availableBank < 2.0*BASE_WAGER){
            wantsSplit=false;
            if(stats!=null)stats.affordabilitySplitFallbacks++;
        }
        ArrayList<Hand> hands=new ArrayList<>();ArrayList<Double> stakes=new ArrayList<>();ArrayList<Boolean> natural=new ArrayList<>();ArrayList<Boolean> splitChild=new ArrayList<>();
        Round out=new Round();
        if(wantsSplit){
            out.splits=1;Hand a=new Hand(),b=new Hand();a.c.add(initial.c.get(0));b.c.add(initial.c.get(1));a.c.add(draw(shoe,ptr));b.c.add(draw(shoe,ptr));
            hands.add(a);hands.add(b);stakes.add(BASE_WAGER);stakes.add(BASE_WAGER);natural.add(false);natural.add(false);splitChild.add(true);splitChild.add(true);
        } else {hands.add(initial);stakes.add(BASE_WAGER);natural.add(true);splitChild.add(false);}

        double committedCapital=hands.size()*BASE_WAGER;
        for(int i=0;i<hands.size();i++){
            Hand h=hands.get(i);boolean first=true;
            ResolvedHandRecord rec=null;
            if(capture){
                rec=new ResolvedHandRecord();rec.cohort=cohort;rec.session=session;rec.round=round;rec.child=i+1;rec.splitChild=splitChild.get(i);
                rec.startTotal=h.total();rec.startSoft=h.soft();rec.dealerUp=dealer.c.get(0);rec.visibleClass=visibleClass(h);rec.startCards=h.cards();rec.startPointer=ptr[0];
                if(h.blackjack()||dealer.blackjack()){rec.textbookAction=Action.NONE;rec.aggressiveAction=Action.NONE;}
                else {rec.textbookAction=textbook(h,dealer.c.get(0),true);rec.aggressiveAction=aggressive?((selective&&h.soft()&&h.total()>=18&&h.total()<=19&&dealer.c.get(0)>=9)?textbook(h,dealer.c.get(0),true):(selective&&!h.soft()&&h.total()>=5&&h.total()<=8&&dealer.c.get(0)>=2&&dealer.c.get(0)<=6)?Action.HIT:(selective&&!h.soft()&&h.total()==9&&dealer.c.get(0)>=9)?Action.HIT:(selective&&!h.soft()&&h.total()==12&&dealer.c.get(0)>=2&&dealer.c.get(0)<=6)?textbook(h,dealer.c.get(0),true):(selective&&h.soft()&&h.total()>=13&&h.total()<=17&&dealer.c.get(0)>=7)?Action.HIT:(selective&&!h.soft()&&h.total()==13&&dealer.c.get(0)>=2&&dealer.c.get(0)<=6)?Action.STAND:(selective&&!h.soft()&&h.total()==8&&dealer.c.get(0)>=7)?Action.HIT:(selective&&!h.soft()&&h.total()>=12&&h.total()<=13&&dealer.c.get(0)>=7)?Action.HIT:(selective&&!h.soft()&&h.total()>=5&&h.total()<=7&&dealer.c.get(0)>=7)?Action.HIT:(selective&&!h.soft()&&h.total()==14)?textbook(h,dealer.c.get(0),true):(selective&&!h.soft()&&h.total()==15)?textbook(h,dealer.c.get(0),true):(selective&&!h.soft()&&h.total()==16)?textbook(h,dealer.c.get(0),true):(selective&&!h.soft()&&splitChild.get(i)&&h.total()==16&&dealer.c.get(0)==11)?Action.HIT:((selective&&!h.soft()&&(h.total()==19||h.total()==18||h.total()==17||(splitChild.get(i)&&h.total()==20)))?Action.STAND:Action.DOUBLE)):rec.textbookAction;}
            }
            if(!h.blackjack()&&!dealer.blackjack())while(!h.bust()){
                Action a=(aggressive&&first)?((selective&&h.soft()&&h.total()>=18&&h.total()<=19&&dealer.c.get(0)>=9)?textbook(h,dealer.c.get(0),true):(selective&&!h.soft()&&h.total()>=5&&h.total()<=8&&dealer.c.get(0)>=2&&dealer.c.get(0)<=6)?Action.HIT:(selective&&!h.soft()&&h.total()==9&&dealer.c.get(0)>=9)?Action.HIT:(selective&&!h.soft()&&h.total()==12&&dealer.c.get(0)>=2&&dealer.c.get(0)<=6)?textbook(h,dealer.c.get(0),true):(selective&&h.soft()&&h.total()>=13&&h.total()<=17&&dealer.c.get(0)>=7)?Action.HIT:(selective&&!h.soft()&&h.total()==13&&dealer.c.get(0)>=2&&dealer.c.get(0)<=6)?Action.STAND:(selective&&!h.soft()&&h.total()==8&&dealer.c.get(0)>=7)?Action.HIT:(selective&&!h.soft()&&h.total()>=12&&h.total()<=13&&dealer.c.get(0)>=7)?Action.HIT:(selective&&!h.soft()&&h.total()>=5&&h.total()<=7&&dealer.c.get(0)>=7)?Action.HIT:(selective&&!h.soft()&&h.total()==14)?textbook(h,dealer.c.get(0),true):(selective&&!h.soft()&&h.total()==15)?textbook(h,dealer.c.get(0),true):(selective&&!h.soft()&&h.total()==16)?textbook(h,dealer.c.get(0),true):(selective&&!h.soft()&&splitChild.get(i)&&h.total()==16&&dealer.c.get(0)==11)?Action.HIT:((selective&&!h.soft()&&(h.total()==19||h.total()==18||h.total()==17||(splitChild.get(i)&&h.total()==20)))?Action.STAND:Action.DOUBLE)):textbook(h,dealer.c.get(0),first);
                if(a==Action.STAND)break;
                if(a==Action.DOUBLE&&first){
                    if(capture && availableBank < committedCapital + BASE_WAGER){
                        if(stats!=null)stats.affordabilityDoubleFallbacks++;
                        Action fb=textbook(h,dealer.c.get(0),true);
                        if(fb==Action.DOUBLE)fb=Action.HIT;
                        if(fb==Action.STAND)break;
                        h.c.add(draw(shoe,ptr));first=false;
                        continue;
                    }
                    stakes.set(i,stakes.get(i)*2.0);committedCapital+=BASE_WAGER;out.doubles++;h.c.add(draw(shoe,ptr));break;
                }
                h.c.add(draw(shoe,ptr));first=false;
            }
            if(capture){rec.endCards=h.cards();rec.stake=stakes.get(i);rec.thirdCardTaken=rec.startCards==2&&rec.endCards>=3;rec.thirdCardBust=rec.thirdCardTaken&&h.bust()&&rec.endCards==3;rec.bust=h.bust();rec.endPointer=ptr[0];out.records.add(rec);}
        }

        boolean live=false;for(Hand h:hands)if(!h.bust())live=true;
        if(live&&!dealer.blackjack())while(dealer.total()<17)dealer.c.add(draw(shoe,ptr));
        for(int i=0;i<hands.size();i++){
            Hand p=hands.get(i);double st=stakes.get(i),net;
            if(natural.get(i)&&p.blackjack()&&!dealer.blackjack())net=1.5*st;
            else if(natural.get(i)&&dealer.blackjack()&&!p.blackjack())net=-st;
            else if(natural.get(i)&&p.blackjack()&&dealer.blackjack())net=0;
            else if(p.bust())net=-st;
            else if(dealer.bust()||p.total()>dealer.total())net=st;
            else if(p.total()<dealer.total())net=-st;
            else net=0;
            out.net+=net;
            if(capture){ResolvedHandRecord rec=out.records.get(i);rec.net=net;rec.outcome=net>0?"WIN":net<0?"LOSS":"PUSH";rec.endPointer=ptr[0];}
        }
        out.win=out.net>0;out.loss=out.net<0;out.push=out.net==0;out.endPointer=ptr[0];return out;
    }

    static PairStats paired(long cohort,String name,List<ResolvedHandRecord> records){
        PairStats s=new PairStats();
        for(int session=0;session<SESSIONS;session++){
            int[] shoe=sixDeckShoe(sessionSeed(cohort,session));if(!auditShoe(shoe))throw new IllegalStateException("Inventory audit failed");
            int pt=0,pa=0;double bt=START_BANK,ba=START_BANK;boolean div=false;int first=0;long tw=0,tl=0,tp=0,aw=0,al=0,ap=0,td=0,ad=0,ts=0,as=0;
            double sessionPeakA=START_BANK,maxDrawdownA=0.0;int sessionPeakHandA=0;
            boolean ever2xA=false,ever3xA=false,ever5xA=false,ever10xA=false,everZeroA=false;
            boolean selectiveStopped=false;
            for(int h=1;h<=HANDS;h++){
                Round rt=playRound(shoe,pt,Profile.TEXTBOOK,name,session+1,h,false,Double.POSITIVE_INFINITY,null);
                pt=rt.endPointer;bt+=rt.net;
                if(rt.win)tw++;else if(rt.loss)tl++;else tp++;td+=rt.doubles;ts+=rt.splits;
                if(bt>s.maxBankT){s.maxBankT=bt;s.maxBankTHand=h;s.maxBankTSession=session+1;}

                if(!selectiveStopped){
                    if(ba < BASE_WAGER){
                        selectiveStopped=true;s.affordabilityBaseStops++;
                        s.aHandsSkippedAfterBankruptcy+=(HANDS-h+1);
                    }
                }
                if(!selectiveStopped){
                    s.totalStarts++;if(pt==pa)s.sameStart++;
                    Round ra=playRound(shoe,pa,Profile.SELECTIVE_AGGRESSION,name,session+1,h,true,ba,s);
                    records.addAll(ra.records);
                    pa=ra.endPointer;ba+=ra.net;
                    if(ra.win)aw++;else if(ra.loss)al++;else ap++;ad+=ra.doubles;as+=ra.splits;
                    if(ba>sessionPeakA){sessionPeakA=ba;sessionPeakHandA=h;}
                    maxDrawdownA=Math.max(maxDrawdownA,sessionPeakA-ba);
                    if(ba>=200)ever2xA=true;if(ba>=300)ever3xA=true;if(ba>=500)ever5xA=true;if(ba>=1000)ever10xA=true;
                    if(ba<=0){
                        everZeroA=true;selectiveStopped=true;s.aBankruptcyStops++;
                        s.aHandsSkippedAfterBankruptcy+=(HANDS-h);
                        ba=0.0;
                    }
                    if(ba>s.maxBankA){s.maxBankA=ba;s.maxBankAHand=h;s.maxBankASession=session+1;}
                    if(!div&&pt!=pa){div=true;first=h;}
                }
                s.aBankAfterHand[h]+=ba;
            }
            if(pt>SHOE_SIZE||pa>SHOE_SIZE)throw new IllegalStateException("Shoe exhausted");
            s.sessions++;s.tEnd+=bt;s.aEnd+=ba;s.tWins+=tw;s.tLosses+=tl;s.tPushes+=tp;s.aWins+=aw;s.aLosses+=al;s.aPushes+=ap;s.tDoubles+=td;s.aDoubles+=ad;s.tSplits+=ts;s.aSplits+=as;
            if(bt>START_BANK)s.tPositive++;else if(bt<START_BANK)s.tNegative++;else s.tEven++;if(ba>START_BANK)s.aPositive++;else if(ba<START_BANK)s.aNegative++;else s.aEven++;
            if(bt>=200)s.t2x++;if(bt>=300)s.t3x++;if(bt>=500)s.t5x++;if(bt>=1000)s.t10x++;
            if(ba>=200)s.a2x++;if(ba>=300)s.a3x++;if(ba>=500)s.a5x++;if(ba>=1000)s.a10x++;
            if(bt>ba)s.tHigher++;else if(ba>bt)s.aHigher++;else s.tie++;
            s.sumSessionPeakA+=sessionPeakA;s.sumMaxDrawdownA+=maxDrawdownA;s.peakHandCountsA[sessionPeakHandA]++;
            if(ever2xA)s.aEver2x++;if(ever3xA)s.aEver3x++;if(ever5xA)s.aEver5x++;if(ever10xA)s.aEver10x++;if(everZeroA)s.aEverZero++;
            if(div){s.diverged++;s.firstDivSum+=first;}if(pt==pa)s.finalSame++;else if(pt>pa)s.tAhead++;else s.aAhead++;s.absDiff+=Math.abs(pt-pa);s.tCards+=pt;s.aCards+=pa;s.maxT=Math.max(s.maxT,pt);s.maxA=Math.max(s.maxA,pa);
        }
        return s;
    }

    static String pct(long a,long b){return String.format(Locale.ROOT,"%.2f%%",b==0?0:100.0*a/b);}
    static String avg(double a,long b){return String.format(Locale.ROOT,"%.3f",b==0?0:a/b);}

    static String baseline(PairStats p,PairStats h){
        StringBuilder r=new StringBuilder();
        r.append("PHASE 3.30 SECOND INTERVENTION RESULTS\n\n");
        for(Object[] z:new Object[][]{{"PRIMARY",p},{"HOLDOUT",h}}){String n=(String)z[0];PairStats s=(PairStats)z[1];
            r.append(n).append("\n");
            r.append("Average ending bankroll Textbook/Selective: ").append(avg(s.tEnd,s.sessions)).append(" / ").append(avg(s.aEnd,s.sessions)).append("\n");
            r.append(String.format(Locale.ROOT,"Maximum bankroll observed Textbook/Selective: %.1f at hand %d (session %d) / %.1f at hand %d (session %d)%n",
                s.maxBankT,s.maxBankTHand,s.maxBankTSession,s.maxBankA,s.maxBankAHand,s.maxBankASession));
            r.append("Positive sessions Textbook/Selective: ").append(pct(s.tPositive,s.sessions)).append(" / ").append(pct(s.aPositive,s.sessions)).append("\n");
            r.append("Affordability base stops: ").append(s.affordabilityBaseStops).append("\n");
            r.append("Affordability split fallbacks: ").append(s.affordabilitySplitFallbacks).append("\n");
            r.append("Affordability double fallbacks: ").append(s.affordabilityDoubleFallbacks).append("\n");
            r.append("Paired winner Textbook/Selective/tie: ").append(pct(s.tHigher,s.sessions)).append(" / ").append(pct(s.aHigher,s.sessions)).append(" / ").append(pct(s.tie,s.sessions)).append("\n");
            r.append("Doubles Textbook/Selective: ").append(s.tDoubles).append(" / ").append(s.aDoubles).append("; splits Textbook/Selective: ").append(s.tSplits).append(" / ").append(s.aSplits).append("\n");
            r.append("Mean cards consumed Textbook/Selective: ").append(avg(s.tCards,s.sessions)).append(" / ").append(avg(s.aCards,s.sessions)).append("\n");
            r.append("Ending bankroll >=2x (200) Textbook/Selective: ").append(pct(s.t2x,s.sessions)).append(" / ").append(pct(s.a2x,s.sessions)).append("\n");
            r.append("Ending bankroll >=3x (300) Textbook/Selective: ").append(pct(s.t3x,s.sessions)).append(" / ").append(pct(s.a3x,s.sessions)).append("\n");
            r.append("Ending bankroll >=5x (500) Textbook/Selective: ").append(pct(s.t5x,s.sessions)).append(" / ").append(pct(s.a5x,s.sessions)).append("\n");
            r.append("Ending bankroll >=10x (1000) Textbook/Selective: ").append(pct(s.t10x,s.sessions)).append(" / ").append(pct(s.a10x,s.sessions)).append("\n\n");
        }
        return r.toString();
    }

    static String multiplierExperiment(PairStats p,PairStats h){
        StringBuilder r=new StringBuilder();
        r.append("PHASE 3.30 BANKRUPTCY-STOP CALIBRATION — CONSTANT 5x\n\n");
        r.append("SCIENTIFIC BOUNDARY\n");
        r.append("Decision policy: frozen Phase 3.20 checkpoint, validated Phase 3.21.\n");
        r.append("Wager architecture: constant 5-unit base wager (5x the Phase 3.22 baseline).\n");
        r.append("One multiplier intervention is active: the base wager is five times the Phase 3.22 baseline (5 units).\n\n");
        for(Object[] z:new Object[][]{{"PRIMARY",p},{"HOLDOUT",h}}){
            String n=(String)z[0];PairStats x=(PairStats)z[1];
            r.append(n).append("\n");
            r.append("Mean ending bankroll: ").append(avg(x.aEnd,x.sessions)).append("\n");
            r.append(String.format(Locale.ROOT,"Maximum bankroll observed anywhere: %.1f at Hand %d (session %d)%n",x.maxBankA,x.maxBankAHand,x.maxBankASession));
            r.append(String.format(Locale.ROOT,"Mean per-session peak bankroll: %.3f%n",x.sumSessionPeakA/x.sessions));
            r.append(String.format(Locale.ROOT,"Mean per-session maximum drawdown: %.3f units%n",x.sumMaxDrawdownA/x.sessions));
            r.append("Sessions ever reaching 2x / 3x / 5x / 10x: ")
             .append(pct(x.aEver2x,x.sessions)).append(" / ").append(pct(x.aEver3x,x.sessions)).append(" / ")
             .append(pct(x.aEver5x,x.sessions)).append(" / ").append(pct(x.aEver10x,x.sessions)).append("\n");
            r.append("Sessions ever reaching bankroll <=0: ").append(pct(x.aEverZero,x.sessions)).append("\n");
            int mode=1;for(int i=2;i<=HANDS;i++)if(x.peakHandCountsA[i]>x.peakHandCountsA[mode])mode=i;
            r.append("Sessions whose highest bankroll never exceeded the 100-unit start: ").append(x.peakHandCountsA[0]).append("\n");
            r.append("Most common positive hand-of-peak among sessions that exceeded start: Hand ").append(mode)
             .append(" [").append(x.peakHandCountsA[mode]).append(" sessions]\n\n");
        }
        r.append("MEAN SELECTIVE BANKROLL TRAJECTORY AFTER EACH HAND\n");
        r.append("Hand | Primary | Holdout\n");
        for(int i=1;i<=HANDS;i++)r.append(String.format(Locale.ROOT,"%2d | %8.3f | %8.3f%n",i,p.aBankAfterHand[i]/p.sessions,h.aBankAfterHand[i]/h.sessions));
        return r.toString();
    }

    static Map<StateKey,StateAgg> aggregate(List<ResolvedHandRecord> rr){
        TreeMap<StateKey,StateAgg> m=new TreeMap<>();
        for(ResolvedHandRecord r:rr){if(r.aggressiveAction==Action.NONE)continue;StateKey k=new StateKey(r.startTotal,r.startSoft,r.dealerUp,r.splitChild,r.textbookAction);m.computeIfAbsent(k,x->new StateAgg()).add(r);}return m;
    }

    static Map<StateKey,StateAgg> aggregateDivergent(List<ResolvedHandRecord> rr){
        TreeMap<StateKey,StateAgg> m=new TreeMap<>();
        for(ResolvedHandRecord r:rr){
            if(r.aggressiveAction==Action.NONE || r.aggressiveAction==r.textbookAction)continue;
            StateKey k=new StateKey(r.startTotal,r.startSoft,r.dealerUp,r.splitChild,r.textbookAction);
            m.computeIfAbsent(k,x->new StateAgg()).add(r);
        }
        return m;
    }

    static String stateReport(String cohort,List<ResolvedHandRecord> rr){
        Map<StateKey,StateAgg> m=aggregate(rr);
        ArrayList<Map.Entry<StateKey,StateAgg>> rows=new ArrayList<>(m.entrySet());
        rows.sort((a,b)->{
            double da=a.getValue().net/a.getValue().hands,db=b.getValue().net/b.getValue().hands;
            int c=Double.compare(da,db);if(c!=0)return c;return Long.compare(b.getValue().hands,a.getValue().hands);
        });
        StringBuilder r=new StringBuilder();
        r.append(cohort).append(" — WORST SELECTIVE-AGGRESSION VISIBLE STATES BY MEAN NET/HAND\n");
        r.append("Rank | Visible state | Hands | Mean net | Loss% | Bust% | 3rd-card bust% of 3rd-card draws | Mean stake\n");
        int rank=0;for(Map.Entry<StateKey,StateAgg> e:rows){if(++rank>25)break;StateAgg a=e.getValue();
            r.append(String.format(Locale.ROOT,"%2d | %-45s | %6d | %+7.3f | %6.2f%% | %6.2f%% | %6.2f%% | %.3f%n",
                rank,e.getKey().label(),a.hands,a.net/a.hands,100.0*a.losses/a.hands,100.0*a.busts/a.hands,a.thirdTaken==0?0:100.0*a.thirdBust/a.thirdTaken,a.stake/a.hands));
        }
        r.append("\n");return r.toString();
    }

    static String summary(List<ResolvedHandRecord> p,List<ResolvedHandRecord> h){
        long pHands=p.size(),hHands=h.size();long pThird=0,pThirdBust=0,hThird=0,hThirdBust=0,pBust=0,hBust=0;double pNet=0,hNet=0,pStake=0,hStake=0;
        EnumMap<Action,Long> pTextbook=new EnumMap<>(Action.class),hTextbook=new EnumMap<>(Action.class);for(Action a:Action.values()){pTextbook.put(a,0L);hTextbook.put(a,0L);}
        for(ResolvedHandRecord r:p){if(r.thirdCardTaken)pThird++;if(r.thirdCardBust)pThirdBust++;if(r.bust)pBust++;pNet+=r.net;pStake+=r.stake;pTextbook.put(r.textbookAction,pTextbook.get(r.textbookAction)+1);}
        for(ResolvedHandRecord r:h){if(r.thirdCardTaken)hThird++;if(r.thirdCardBust)hThirdBust++;if(r.bust)hBust++;hNet+=r.net;hStake+=r.stake;hTextbook.put(r.textbookAction,hTextbook.get(r.textbookAction)+1);}
        return "PHASE 3.30 — SELECTIVE-AGGRESSION INSTRUMENTATION SUMMARY\n\n"+
            "PRIMARY resolved selective-aggression hands: "+pHands+"; mean net/hand "+String.format(Locale.ROOT,"%+.4f",pNet/pHands)+"; mean committed stake "+String.format(Locale.ROOT,"%.4f",pStake/pHands)+"; bust rate "+pct(pBust,pHands)+"; third-card bust rate when a third card was taken "+pct(pThirdBust,pThird)+".\n"+
            "Textbook would have chosen on those same visible first-decision states: HIT "+pTextbook.get(Action.HIT)+", STAND "+pTextbook.get(Action.STAND)+", DOUBLE "+pTextbook.get(Action.DOUBLE)+".\n\n"+
            "HOLDOUT resolved selective-aggression hands: "+hHands+"; mean net/hand "+String.format(Locale.ROOT,"%+.4f",hNet/hHands)+"; mean committed stake "+String.format(Locale.ROOT,"%.4f",hStake/hHands)+"; bust rate "+pct(hBust,hHands)+"; third-card bust rate when a third card was taken "+pct(hThirdBust,hThird)+".\n"+
            "Textbook would have chosen on those same visible first-decision states: HIT "+hTextbook.get(Action.HIT)+", STAND "+hTextbook.get(Action.STAND)+", DOUBLE "+hTextbook.get(Action.DOUBLE)+".\n\n"+
            "INTERPRETATION\nPhase 3.30 carries forward split-child HARD 20 STAND, HARD 19 STAND, and split-child HARD 18 STAND. It adds one new family only: NO POLICY OR WAGER INTERVENTION; frozen policy carried forward at 1x. All other Maximum Aggression behaviour remains frozen.\n";
    }

    static String replicatedCandidates(List<ResolvedHandRecord> primary,List<ResolvedHandRecord> holdout){
        Map<StateKey,StateAgg> p=aggregateDivergent(primary),h=aggregateDivergent(holdout);
        final class C {StateKey k;StateAgg a,b;double score;C(StateKey k,StateAgg a,StateAgg b){this.k=k;this.a=a;this.b=b;this.score=(a.net/a.hands+b.net/b.hands)/2.0;}}
        ArrayList<C> c=new ArrayList<>();
        for(StateKey k:p.keySet())if(h.containsKey(k)){StateAgg a=p.get(k),b=h.get(k);if(a.hands>=100&&b.hands>=100&&a.net/a.hands<0&&b.net/b.hands<0)c.add(new C(k,a,b));}
        c.sort(Comparator.comparingDouble(x->x.score));
        StringBuilder r=new StringBuilder("PHASE 3.30 — REMAINING TRUE POLICY-DIVERGENCE STATES UNDER FROZEN 3.20 POLICY\n\n");
        r.append("Filter: aggregate ONLY hands where Selective Aggression's recorded first action differs from the frozen Textbook first action; then require the same visible state >=100 times in BOTH cohorts and negative mean net/hand in BOTH cohorts. This prevents already-protected states with negative realised outcomes from being mislabelled as remaining policy damage.\n\n");
        r.append("Rank | State | Primary n / net | Holdout n / net | P bust% / H bust% | Textbook first action\n");
        int rank=0;for(C x:c){if(++rank>20)break;r.append(String.format(Locale.ROOT,"%2d | %-34s | %5d / %+6.3f | %5d / %+6.3f | %6.2f%% / %6.2f%% | %s%n",rank,(x.k.soft?"SOFT ":"HARD ")+x.k.total+" vs "+x.k.up+(x.k.splitChild?" [split-child]":""),x.a.hands,x.a.net/x.a.hands,x.b.hands,x.b.net/x.b.hands,100.0*x.a.busts/x.a.hands,100.0*x.b.busts/x.b.hands,x.k.textbook));}
        r.append("\nDESIGN USE\nPhase 3.30 carries forward the validated split-child HARD 20, HARD 19 and split-child HARD 18 protections and adds no intervention; frozen decision policy is measured at the unchanged 1x wager. Remaining replicated damage states are retained for later one-rule-at-a-time interventions.\n");
        return r.toString();
    }

    static String methodology(){
        return "PHASE 3.30 — RUNNING TXT AUDIT RECORD\n\n"+
            "OBJECTIVE\nMake the fourth controlled stabilisation intervention while preserving the frozen architecture. Carry forward the three validated protections, then add one new policy family: HARD 16 follows its corresponding Textbook action rather than taking Maximum Aggression's automatic DOUBLE.\n\n"+
            "EVIDENCE HIERARCHY\n1. Primary design authority: finite six-deck Phase 2.xx evidence and new Phase 3.xx data.\n2. Earlier non-depleting/infinite-generator behaviour-profile data: historical corroboration and hypothesis generation only.\n3. Old behaviour-profile evidence must not directly define a new policy unless finite-shoe evidence independently supports the same conclusion.\n\n"+
            "FROZEN VARIABLES\nSix decks, deterministic session shuffle, 30 hands, 100-unit start, 1-unit base wager, dealer rules, blackjack payout, split limit, no in-session reshuffle, textbook control and Maximum Aggression policy are unchanged from Phase 2.02.\n\n"+
            "POLICY INFORMATION BOUNDARY\nThe future optimiser may use player hand composition/total, pair status, dealer upcard and legal actions. Phase 3.30 deliberately uses no previous-card-history, running count, remaining-rank inventory, hidden card or future-card feature. The accumulated policy uses only current visible states: split-child HARD 20, HARD 19, HARD 18, split-child HARD 16 vs Ace, and HARD 17. No card-history or composition feature is introduced.\n\n"+
            "PHASE 3.30 DECISION RULE\nCarry forward split-child HARD 20 STAND, HARD 19 STAND and split-child HARD 18 STAND. ONE additional Phase 3.30 intervention: if an ordinary first-decision hand is hard (not soft) and totals 18, Selective Aggression STANDS. Otherwise the frozen Maximum Aggression policy is unchanged. Textbook remains the control.\n";
    }

    static String hash(String s)throws Exception{MessageDigest md=MessageDigest.getInstance("SHA-256");byte[] d=md.digest(s.getBytes(StandardCharsets.UTF_8));StringBuilder b=new StringBuilder();for(byte x:d)b.append(String.format("%02x",x));return b.toString();}
    static void write(String n,String s)throws Exception{Files.writeString(Path.of(n),s,StandardCharsets.UTF_8);}
    static void writeCsv(String n,List<ResolvedHandRecord> rr)throws Exception{StringBuilder b=new StringBuilder("cohort,session,round,child,split_child,start_total,start_soft,dealer_up,visible_class,textbook_first_action,aggressive_first_action,start_cards,end_cards,stake,third_card_taken,third_card_bust,bust,outcome,net,start_pointer,end_pointer\n");for(ResolvedHandRecord r:rr)b.append(r.csv()).append('\n');write(n,b.toString());}

    public static void main(String[] args)throws Exception{
        if(!auditShoe(sixDeckShoe(1)))throw new IllegalStateException("Initial inventory audit failed");
        ArrayList<ResolvedHandRecord> primary=new ArrayList<>(),holdout=new ArrayList<>();
        PairStats p=paired(PRIMARY_SEED,"PRIMARY",primary),h=paired(HOLDOUT_SEED,"HOLDOUT",holdout);
        String base=baseline(p,h),multi=multiplierExperiment(p,h),sum=summary(primary,holdout),states=stateReport("PRIMARY",primary)+stateReport("HOLDOUT",holdout),rep=replicatedCandidates(primary,holdout),audit=methodology();
        String combined=base+"\n"+multi+"\n"+sum+"\n"+states+"\n"+rep+"\n"+audit;
        String fp=hash(combined);
        write("Phase_3_30_Intervention_Results.txt",base);
        write("Phase_3_30_Bankruptcy_Stop_5x_Results.txt",multi);
        write("Phase_3_30_Instrumentation_Summary.txt",sum);
        write("Phase_3_30_State_Damage_Ranking.txt",states);
        write("Phase_3_30_Remaining_Candidate_States.txt",rep);
        write("Phase_3_30_Running_Audit_Record.txt",audit);
        writeCsv("Phase_3_30_Primary_Resolved_Hands.csv",primary);
        writeCsv("Phase_3_30_Holdout_Resolved_Hands.csv",holdout);
        write("Phase_3_30_Replay_Verification.txt","PHASE 3.30 DETERMINISTIC REPLAY VERIFICATION\n\nPrimary seed: "+PRIMARY_SEED+"\nHoldout seed: "+HOLDOUT_SEED+"\nSessions per cohort: "+SESSIONS+"\nHands per session: "+HANDS+"\nEvidence SHA-256: "+fp+"\n");
        write("Phase_3_30_README.txt","DETERMINISTIC BLACKJACK PHASE 3.30 PACKAGE\n\nStart with Phase_3_30_Running_Audit_Record.txt, then Phase_3_30_Intervention_Results.txt, Phase_3_30_Instrumentation_Summary.txt, Phase_3_30_Remaining_Candidate_States.txt and Phase_3_30_State_Damage_Ranking.txt. The two CSV files are the state-level primary and holdout evidence datasets.\n");
        System.out.print(combined+"\nPHASE 3.30 REPLAY FINGERPRINT: "+fp+"\n");
    }
}
