/*
===============================================================================
DETERMINISTIC BLACKJACK DECISION ENGINE RESEARCH
PHASE 1.20 — EVIDENCE-BASED PATTERN CONFIDENCE

CODE VERSION: Deterministic Blackjack Phase 1.20
CODE BUILD TAG: DBDE-1.20-EVIDENCE-CONFIDENCE-TIERS

RESEARCH BOUNDARY
Only visible cards available at the decision moment may influence a model.
Hidden cards are inspected afterwards solely to score prediction accuracy.
No running count, remaining-shoe estimate or live gambling assistance is used.
===============================================================================
*/
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.MessageDigest;
import java.util.*;

public final class DeterministicBlackjackPhase120 {
    static final int SESSIONS = 10_000, HANDS = 100;
    static final long PRIMARY_SEED = 120_001L, HOLDOUT_SEED = 120_101L;
    static final double START = 100.0, BET = 1.0;
    enum Action { HIT, STAND, DOUBLE }
    enum Branch { CONTROL, LOW_SEQUENCE, HIGH_SEQUENCE, COMBINED }
    record Model(String label, Branch branch, int threshold) {}
    static final List<Model> MODELS = List.of(
        new Model("Textbook control", Branch.CONTROL, 0),
        new Model("Low-card confidence T1", Branch.LOW_SEQUENCE, 3),
        new Model("Low-card confidence T2", Branch.LOW_SEQUENCE, 4),
        new Model("Low-card confidence T3", Branch.LOW_SEQUENCE, 5),
        new Model("Low-card confidence T4", Branch.LOW_SEQUENCE, 6),
        new Model("High-card confidence T1", Branch.HIGH_SEQUENCE, 3),
        new Model("High-card confidence T2", Branch.HIGH_SEQUENCE, 4),
        new Model("High-card confidence T3", Branch.HIGH_SEQUENCE, 5),
        new Model("High-card confidence T4", Branch.HIGH_SEQUENCE, 6),
        new Model("Combined confidence T2", Branch.COMBINED, 4)
    );

    static final class Hand {
        final List<Integer> cards = new ArrayList<>();
        double wager = BET;
        int total(){ int t=0,a=0; for(int c:cards){t+=c;if(c==11)a++;} while(t>21&&a-->0)t-=10; return t; }
        boolean soft(){ int raw=0; for(int c:cards)raw+=c; return cards.contains(11)&&raw==total(); }
        boolean bust(){ return total()>21; }
        boolean blackjack(){ return cards.size()==2&&total()==21; }
    }
    static final class VisibleHistory {
        final ArrayDeque<Integer> cards = new ArrayDeque<>();
        void add(int c){ cards.addLast(c); if(cards.size()>30)cards.removeFirst(); }
        int trailing(List<Integer> current, int up, boolean low){
            ArrayList<Integer> all=new ArrayList<>(cards); all.add(up); all.addAll(current);
            int n=0; for(int i=all.size()-1;i>=0;i--){ int c=all.get(i); boolean q=low?(c>=2&&c<=7):(c>=8&&c<=11); if(!q)break; n++; } return n;
        }
        int trailingHistory(boolean low){
            int n=0; Iterator<Integer> it=cards.descendingIterator(); while(it.hasNext()){int c=it.next();boolean q=low?(c>=2&&c<=7):(c>=8&&c<=11);if(!q)break;n++;}return n;
        }
    }
    static final class Stats {
        double totalEnding, totalStaked, totalMaxDrawdown;
        long winningSessions, losingSessions, evenSessions, wins, losses, pushes;
        long activations, changedBetter, changedWorse, changedSame;
        long lowPredictionOpportunities, hiddenHigh, nextDealerHighEligible, nextDealerHigh, dealerBust;
        long highPredictionOpportunities, safeHit, hitBust, hitImproved;
        final StringBuilder log = new StringBuilder();
        final StringBuilder ledger = new StringBuilder();
    }
    static final class SessionResult { double ending, staked, drawdown; long wins,losses,pushes; }
    static final class Decision { Action baseline, chosen; int lowRun, highRun; String reason=""; }

    static Action basic(Hand h,int up){
        int t=h.total();
        if(h.soft()){
            if(t>=19)return Action.STAND;
            if(t==18)return (up>=3&&up<=6)?Action.DOUBLE:(up>=9?Action.HIT:Action.STAND);
            if(t==17)return (up>=3&&up<=6)?Action.DOUBLE:Action.HIT;
            if(t==16||t==15)return (up>=4&&up<=6)?Action.DOUBLE:Action.HIT;
            if(t==14||t==13)return (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 up==11?Action.HIT:Action.DOUBLE;
        if(t==10)return up<=9?Action.DOUBLE:Action.HIT;
        if(t==9)return (up>=3&&up<=6)?Action.DOUBLE:Action.HIT;
        return Action.HIT;
    }
    static Decision decide(Model model, Hand h, int up, VisibleHistory hist){
        Decision d=new Decision(); d.baseline=basic(h,up); d.chosen=d.baseline;
        d.lowRun=hist.trailing(h.cards,up,true); d.highRun=hist.trailingHistory(false);
        boolean hard=!h.soft(); int t=h.total();
        if(hard && (model.branch==Branch.LOW_SEQUENCE||model.branch==Branch.COMBINED)
                && d.lowRun>=model.threshold && d.baseline==Action.HIT && t>=12&&t<=16 && up>=7){
            d.chosen=Action.STAND; d.reason="LOW_SEQUENCE_EXPECT_HIGH";
        }
        if(hard && (model.branch==Branch.HIGH_SEQUENCE||model.branch==Branch.COMBINED)
                && d.highRun>=model.threshold && d.baseline==Action.STAND && (t==15||t==16) && up>=2&&up<=6){
            d.chosen=Action.HIT; d.reason="HIGH_SEQUENCE_EXPECT_LOW";
        }
        return d;
    }
    static int card(Random r){ int x=r.nextInt(52); if(x<4)return 11; int rank=x/4+1; return Math.min(Math.max(rank,2),10); }
    static boolean high(int c){return c>=8;}
    static long handSeed(long cohort,int session,int hand){return cohort+session*1_000_003L+hand*10_007L;}

    static SessionResult playSession(Model model,long cohort,int sn,Stats s){
        double bankroll=START,peak=START,maxDD=0,staked=0; long sw=0,sl=0,sp=0;
        VisibleHistory hist=new VisibleHistory();
        for(int hn=1;hn<=HANDS;hn++){
            Random r=new Random(handSeed(cohort,sn,hn));
            Hand p=new Hand(), d=new Hand();
            p.cards.add(card(r)); d.cards.add(card(r)); p.cards.add(card(r)); d.cards.add(card(r));
            int up=d.cards.get(0), hidden=d.cards.get(1);
            boolean changed=false; Decision changedDecision=null; int beforeTotal=p.total();
            while(!p.bust()){
                Decision dec=decide(model,p,up,hist);
                if(dec.chosen!=dec.baseline && !changed){changed=true;changedDecision=dec;beforeTotal=p.total();s.activations++;}
                if(dec.chosen==Action.STAND)break;
                if(dec.chosen==Action.DOUBLE && p.cards.size()==2){p.wager*=2;p.cards.add(card(r));break;}
                p.cards.add(card(r));
            }
            int dealerNext=-1;
            while(d.total()<17){int c=card(r);if(dealerNext<0)dealerNext=c;d.cards.add(c);}
            double delta=resolve(p,d); bankroll+=delta;staked+=p.wager;peak=Math.max(peak,bankroll);maxDD=Math.max(maxDD,peak-bankroll);
            if(delta>0){sw++;s.wins++;}else if(delta<0){sl++;s.losses++;}else{sp++;s.pushes++;}

            // Prediction evidence is logged even when the belief supports textbook standing.
            int lowRun=hist.trailing(p.cards,up,true);
            if(model.branch!=Branch.CONTROL && (model.branch==Branch.LOW_SEQUENCE||model.branch==Branch.COMBINED)
                    && lowRun>=model.threshold && up>=2&&up<=6){
                s.lowPredictionOpportunities++; if(high(hidden))s.hiddenHigh++; if(dealerNext>=0){s.nextDealerHighEligible++;if(high(dealerNext))s.nextDealerHigh++;} if(d.bust())s.dealerBust++;
            }
            if(changed && changedDecision.reason.equals("HIGH_SEQUENCE_EXPECT_LOW")){
                s.highPredictionOpportunities++; if(!p.bust())s.safeHit++; if(p.bust())s.hitBust++; if(!p.bust()&&p.total()>beforeTotal)s.hitImproved++;
            }
            if(changed){
                double baselineDelta=counterfactual(changedDecision.baseline, p.cards.subList(0,Math.min(2,p.cards.size())), up, hidden, handSeed(cohort,sn,hn)+777);
                if(delta>baselineDelta)s.changedBetter++;else if(delta<baselineDelta)s.changedWorse++;else s.changedSame++;
                if(s.log.length()<16000)s.log.append("Session ").append(sn).append(" hand ").append(hn)
                    .append(" | player ").append(p.cards).append(" dealer ").append(d.cards)
                    .append(" | low-run ").append(changedDecision.lowRun).append(" high-run ").append(changedDecision.highRun)
                    .append(" | textbook ").append(changedDecision.baseline).append(" intuition ").append(changedDecision.chosen)
                    .append(" | ").append(changedDecision.reason).append(" | result £").append(String.format(Locale.ROOT,"%.2f",delta)).append('\n');
            }
            hist.add(p.cards.get(0)); if(p.cards.size()>1)hist.add(p.cards.get(1)); for(int i=2;i<p.cards.size();i++)hist.add(p.cards.get(i)); hist.add(up); hist.add(hidden); for(int i=2;i<d.cards.size();i++)hist.add(d.cards.get(i));
            if(s.ledger.length()<200_000) s.ledger.append(sn).append('|').append(hn).append('|').append(model.label).append('|').append(p.cards).append('|').append(d.cards).append('|').append(delta).append('\n');
        }
        SessionResult x=new SessionResult();x.ending=bankroll;x.staked=staked;x.drawdown=maxDD;x.wins=sw;x.losses=sl;x.pushes=sp;return x;
    }
    static double resolve(Hand p,Hand d){if(p.blackjack()&&!d.blackjack())return 1.5*p.wager;if(d.blackjack()&&!p.blackjack())return-p.wager;if(p.bust())return-p.wager;if(d.bust()||p.total()>d.total())return p.wager;if(p.total()<d.total())return-p.wager;return 0;}
    static double counterfactual(Action a,List<Integer> start,int up,int hidden,long seed){
        Random r=new Random(seed);Hand p=new Hand(),d=new Hand();p.cards.addAll(start);d.cards.add(up);d.cards.add(hidden);
        if(a==Action.DOUBLE){p.wager=2;p.cards.add(card(r));}else if(a==Action.HIT){while(!p.bust()&&basic(p,up)==Action.HIT)p.cards.add(card(r));}
        while(d.total()<17)d.cards.add(card(r));return resolve(p,d);
    }
    static Stats run(Model model,long seed){Stats s=new Stats();for(int sn=1;sn<=SESSIONS;sn++){SessionResult x=playSession(model,seed,sn,s);s.totalEnding+=x.ending;s.totalStaked+=x.staked;s.totalMaxDrawdown+=x.drawdown;if(x.ending>START)s.winningSessions++;else if(x.ending<START)s.losingSessions++;else s.evenSessions++;}return s;}
    static String fingerprint(Stats s){return sha(s.totalEnding+"|"+s.totalStaked+"|"+s.wins+"|"+s.losses+"|"+s.pushes+"|"+s.activations+"|"+s.lowPredictionOpportunities+"|"+s.highPredictionOpportunities+"|"+sha(s.ledger.toString()));}
    static String sha(String x){try{byte[] b=MessageDigest.getInstance("SHA-256").digest(x.getBytes(StandardCharsets.UTF_8));StringBuilder z=new StringBuilder();for(byte q:b)z.append(String.format(Locale.ROOT,"%02x",q));return z.toString();}catch(Exception e){throw new IllegalStateException(e);}}
    static void write(String n,String x)throws IOException{Files.writeString(Path.of(n),x,StandardCharsets.UTF_8);}
    static String summary(Model m,Stats s){return String.format(Locale.ROOT,"%-27s | avg ending £%6.2f | winning/losing/even %d/%d/%d | avg drawdown £%5.2f | activations %d",m.label,s.totalEnding/SESSIONS,s.winningSessions,s.losingSessions,s.evenSessions,s.totalMaxDrawdown/SESSIONS,s.activations);}
    static double pct(long a,long b){return b==0?0:100.0*a/b;}

    public static void main(String[] args)throws Exception{
        Map<Model,Stats> primary=new LinkedHashMap<>(), replay=new LinkedHashMap<>(), holdout=new LinkedHashMap<>();
        for(Model m:MODELS){primary.put(m,run(m,PRIMARY_SEED));replay.put(m,run(m,PRIMARY_SEED));holdout.put(m,run(m,HOLDOUT_SEED));}
        boolean pass=true;for(Model m:MODELS)pass&=fingerprint(primary.get(m)).equals(fingerprint(replay.get(m)));
        StringBuilder out=new StringBuilder();
        out.append("DETERMINISTIC BLACKJACK DECISION ENGINE RESEARCH\nPHASE 1.20 — EVIDENCE-BASED PATTERN CONFIDENCE\n\n");
        out.append("LAYMAN PURPOSE\n--------------\nThis phase studies a familiar table feeling. After several low cards, a player may suspect that the dealer's hidden card and next draw are likely to be high. After several high cards, a player may feel that hitting 15 or 16 is safer because a lower card seems due. The simulator measures the visible evidence, the confidence threshold and what actually happened.\n\n");
        out.append("CONFIDENCE TIERS\n----------------\nTier 1 = 3 consecutive qualifying visible cards.\nTier 2 = 4.\nTier 3 = 5.\nTier 4 = 6 or more.\nLow cards are 2–7. High cards are 8–Ace. These tiers describe accumulated visible evidence, not a claimed probability.\n\n");
        out.append("PRIMARY SESSION RESULTS\n-----------------------\n");for(Model m:MODELS)out.append(summary(m,primary.get(m))).append('\n');
        out.append("\nLOW-CARD EXPECTATION EVIDENCE\n-----------------------------\n");
        for(Model m:MODELS){if(m.branch==Branch.LOW_SEQUENCE||m.branch==Branch.COMBINED){Stats s=primary.get(m);out.append(String.format(Locale.ROOT,"%-27s | opportunities %d | hidden card high %.2f%% | next dealer draw high %.2f%% | dealer bust %.2f%%\n",m.label,s.lowPredictionOpportunities,pct(s.hiddenHigh,s.lowPredictionOpportunities),pct(s.nextDealerHigh,s.nextDealerHighEligible),pct(s.dealerBust,s.lowPredictionOpportunities)));}}
        out.append("\nHIGH-CARD EXPECTATION: HITTING 15 OR 16\n---------------------------------------\n");
        for(Model m:MODELS){if(m.branch==Branch.HIGH_SEQUENCE||m.branch==Branch.COMBINED){Stats s=primary.get(m);out.append(String.format(Locale.ROOT,"%-27s | opportunities %d | extra hit survived %.2f%% | bust %.2f%% | hand improved %.2f%%\n",m.label,s.highPredictionOpportunities,pct(s.safeHit,s.highPredictionOpportunities),pct(s.hitBust,s.highPredictionOpportunities),pct(s.hitImproved,s.highPredictionOpportunities)));}}
        out.append("\nCHANGED-DECISION COMPARISON\n---------------------------\n");for(Model m:MODELS){Stats s=primary.get(m);if(s.activations>0)out.append(String.format(Locale.ROOT,"%-27s | better/worse/same %d/%d/%d\n",m.label,s.changedBetter,s.changedWorse,s.changedSame));}
        out.append("\nHOLDOUT SESSION RESULTS\n-----------------------\n");for(Model m:MODELS)out.append(summary(m,holdout.get(m))).append('\n');
        out.append("\nLAYMAN INTERPRETATION\n--------------------\nA stronger-looking run can make a belief feel more convincing. Phase 1.20 does not treat confidence as proof. It asks three separate questions: Was the prediction right? Was changing the decision better? Did the whole 100-hand session finish better? A memorable successful hit or dealer bust must be compared with every unsuccessful activation.\n\n");
        out.append("ETHICAL AND INFORMATION BOUNDARY\n--------------------------------\nOnly cards visible to the player at the decision moment can create confidence. The dealer's hidden card is examined afterwards solely to score the prediction. No running count, remaining-shoe estimate, hidden information or live gambling assistance is provided. This is research software, not a recommendation to gamble.\n\nREPLAY STATUS: ").append(pass?"PASS":"FAIL").append('\n');
        write("Phase_1_20_Evidence_Based_Confidence_Results.txt",out.toString());
        write("Phase_1_20_Layman_Explanation.txt","PHASE 1.20 — LAYMAN EXPLANATION\n\nPeople often become more confident after seeing a longer run of similar cards. This phase gives that confidence a visible evidence threshold: three, four, five or six consecutive low or high cards. It then checks whether the player's expectation was correct, whether changing the textbook action helped, and whether the full session improved.\n\nThe experiment studies intuition respectfully. It does not describe the player as irrational and does not offer a real-casino system.\n");
        StringBuilder log=new StringBuilder("PHASE 1.20 — SAMPLE CONFIDENCE-DRIVEN DECISIONS\n\n");for(Model m:MODELS){if(m.branch!=Branch.CONTROL){log.append("=== ").append(m.label).append(" ===\n").append(primary.get(m).log).append('\n');}}write("Phase_1_20_Confidence_Decision_Log.txt",log.toString());
        StringBuilder rep=new StringBuilder("PHASE 1.20 — DETERMINISTIC REPLAY VERIFICATION\n\n");for(Model m:MODELS)rep.append(m.label).append("\nfirst:  ").append(fingerprint(primary.get(m))).append("\nreplay: ").append(fingerprint(replay.get(m))).append("\nresult: ").append(fingerprint(primary.get(m)).equals(fingerprint(replay.get(m)))?"PASS":"FAIL").append("\n\n");rep.append("OVERALL: ").append(pass?"PASS":"FAIL").append('\n');write("Phase_1_20_Replay_Verification.txt",rep.toString());
        write("Phase_1_20_README.txt","PHASE 1.20 PACKAGE — EVIDENCE-BASED PATTERN CONFIDENCE\n\nStart with Phase_1_20_Evidence_Based_Confidence_Results.txt.\n\nFiles:\n- DeterministicBlackjackPhase120.java\n- Phase_1_20_Evidence_Based_Confidence_Results.txt\n- Phase_1_20_Layman_Explanation.txt\n- Phase_1_20_Confidence_Decision_Log.txt\n- Phase_1_20_Replay_Verification.txt\n- output.txt\n- compile_errors.txt\n- Preserved_Phase_1_19/\n\nNo guide is created during the research programme.\n");
        System.out.print(out);
    }
}
