/*
===============================================================================
DETERMINISTIC BLACKJACK DECISION ENGINE RESEARCH
PHASE 3.03 - FIRST CONTROLLED STABILISATION INTERVENTION

CODE VERSION: Deterministic Blackjack Phase 3.03
CODE BUILD TAG: DBDE-3.03-HARD20-SPLIT-CHILD-STAND

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

PURPOSE
Phase 3.03 is the first genuine policy-optimisation intervention. It changes
ONE replicated visible-state family only: after an initial split has already
occurred, a split-child HARD 20 that reaches its first decision will STAND
instead of taking Maximum Aggression's otherwise automatic DOUBLE.

WHY THIS FAMILY
Phase 3.02 finite-shoe Primary and Holdout evidence ranked split-child HARD 20
states as the most consistently damaging adequately sampled family. Across
dealer upcards, these states lost roughly 1.65-1.77 units per resolved hand
and busted about 91-93% of the time under the aggressive DOUBLE, while the
Textbook action for the same visible state is STAND.

FROZEN CONTROLS
- Six exact decks (312 cards), deterministically shuffled once per session.
- 30 hands per session; 100-unit starting bankroll; flat 1-unit base wager.
- Textbook controller unchanged.
- Initial Maximum Aggression split precedence unchanged: all equal stored
  values split first; 10/J/Q/K are all stored as value 10.
- All other Maximum Aggression first-decision states still DOUBLE.
- One split only; doubling after a split remains permitted in all other states.
- Dealer stands on all 17 including soft 17; natural blackjack pays 3:2.
- No surrender; no reshuffle inside the 30-hand session.
- No card counting, previous-card-history feature, remaining-shoe composition,
  hidden-card knowledge, future-card knowledge or adaptive learning in-run.

NEW OBSERVATIONAL OUTCOMES
Phase 3.03 records ending-bankroll thresholds >100, >=200 (2x), >=300 (3x),
>=500 (5x) and >=1000 (10x). These metrics DO NOT influence the policy.
===============================================================================
*/
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.MessageDigest;
import java.util.*;

public final class DeterministicBlackjackPhase303 {
    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 = 1.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;
    }

    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){
        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)));
        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);}

        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&&splitChild.get(i)&&!h.soft()&&h.total()==20)?Action.STAND:Action.DOUBLE):rec.textbookAction;}
            }
            if(!h.blackjack()&&!dealer.blackjack())while(!h.bust()){
                Action a=(aggressive&&first)?((selective&&splitChild.get(i)&&!h.soft()&&h.total()==20)?Action.STAND:Action.DOUBLE):textbook(h,dealer.c.get(0),first);
                if(a==Action.STAND)break;
                if(a==Action.DOUBLE&&first){stakes.set(i,stakes.get(i)*2.0);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;
            for(int h=1;h<=HANDS;h++){
                s.totalStarts++;if(pt==pa)s.sameStart++;
                Round rt=playRound(shoe,pt,Profile.TEXTBOOK,name,session+1,h,false);
                Round ra=playRound(shoe,pa,Profile.SELECTIVE_AGGRESSION,name,session+1,h,true);
                records.addAll(ra.records);
                pt=rt.endPointer;pa=ra.endPointer;bt+=rt.net;ba+=ra.net;
                if(rt.win)tw++;else if(rt.loss)tl++;else tp++;if(ra.win)aw++;else if(ra.loss)al++;else ap++;
                td+=rt.doubles;ad+=ra.doubles;ts+=rt.splits;as+=ra.splits;
                if(!div&&pt!=pa){div=true;first=h;}
            }
            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++;
            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.03 FIRST 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("Positive sessions Textbook/Selective: ").append(pct(s.tPositive,s.sessions)).append(" / ").append(pct(s.aPositive,s.sessions)).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 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 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.03 — 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.03 changes one policy family only: split-child HARD 20 now STANDS instead of automatically DOUBLING. All other Maximum Aggression behaviour remains frozen. The purpose is to measure whether removing this single replicated damage mechanism improves the 30-hand bankroll distribution.\n";
    }

    static String replicatedCandidates(List<ResolvedHandRecord> primary,List<ResolvedHandRecord> holdout){
        Map<StateKey,StateAgg> p=aggregate(primary),h=aggregate(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.03 — REMAINING REPLICATED DAMAGE STATES\n\n");
        r.append("Filter: same visible state appears >=100 times in BOTH primary and holdout, and Selective Aggression has negative mean net/hand in BOTH cohorts. This avoids choosing later interventions from tiny-sample extremes.\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.03 has removed only the split-child HARD 20 automatic DOUBLE. Remaining replicated damage states are retained as evidence for a later one-rule-at-a-time intervention; no second rule is changed here.\n");
        return r.toString();
    }

    static String methodology(){
        return "PHASE 3.03 — RUNNING TXT AUDIT RECORD\n\n"+
            "OBJECTIVE\nMake the first controlled stabilisation intervention while preserving the Phase 3.02 frozen architecture: split-child HARD 20 STANDS 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.03 deliberately uses no previous-card-history, running count, remaining-rank inventory, hidden card or future-card feature. The new rule depends only on the current visible split-child HARD 20 state.\n\n"+
            "PHASE 3.03 DECISION RULE\nONE intervention only: if the hand is a split child, is hard (not soft), totals 20, and is at its first decision, 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),sum=summary(primary,holdout),states=stateReport("PRIMARY",primary)+stateReport("HOLDOUT",holdout),rep=replicatedCandidates(primary,holdout),audit=methodology();
        String combined=base+"\n"+sum+"\n"+states+"\n"+rep+"\n"+audit;
        String fp=hash(combined);
        write("Phase_3_03_Intervention_Results.txt",base);
        write("Phase_3_03_Instrumentation_Summary.txt",sum);
        write("Phase_3_03_State_Damage_Ranking.txt",states);
        write("Phase_3_03_Remaining_Candidate_States.txt",rep);
        write("Phase_3_03_Running_Audit_Record.txt",audit);
        writeCsv("Phase_3_03_Primary_Resolved_Hands.csv",primary);
        writeCsv("Phase_3_03_Holdout_Resolved_Hands.csv",holdout);
        write("Phase_3_03_Replay_Verification.txt","PHASE 3.03 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_03_README.txt","DETERMINISTIC BLACKJACK PHASE 3.03 PACKAGE\n\nStart with Phase_3_03_Running_Audit_Record.txt, then Phase_3_03_Intervention_Results.txt, Phase_3_03_Instrumentation_Summary.txt, Phase_3_03_Remaining_Candidate_States.txt and Phase_3_03_State_Damage_Ranking.txt. The two CSV files are the state-level primary and holdout evidence datasets.\n");
        System.out.print(combined+"\nPHASE 3.03 REPLAY FINGERPRINT: "+fp+"\n");
    }
}
