import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.regex.*;

public class UniversalTerminalChronologyAudit {
  static final Pattern ROW=Pattern.compile("^#\\d+ \\| H(\\d+) \\| (.*?)\\s+\\|\\s+(.+?)\\s*$");
  static int value(String c){String x=c.trim().replaceAll("[♠♥♦♣SHDC?U]$","");if(x.equals("A"))return 11;if(x.matches("10|J|Q|K"))return 10;try{return Integer.parseInt(x);}catch(Exception e){return 0;}}
  static int total(List<String> cs){int t=0,a=0;for(String c:cs){int v=value(c);t+=v;if(v==11)a++;}while(t>21&&a-->0)t-=10;return t;}
  public static void main(String[] args)throws Exception{
    Path root=Paths.get(args.length>0?args[0]:"../CLI/session_evidence");
    List<String> findings=new ArrayList<>(); int files=0,hands=0;
    try(DirectoryStream<Path> ds=Files.newDirectoryStream(root,"blackjack_live_session_*.txt")){
      for(Path p:ds){files++;Map<Integer,List<String[]>> by=new LinkedHashMap<>();
        Set<Integer> closed=new HashSet<>(); Integer active=null;
        for(String line:Files.readAllLines(p,StandardCharsets.UTF_8)){
          Matcher hm=Pattern.compile("^HAND (\\d+) DEAL-ORDER RECONSTRUCTION$").matcher(line.trim());
          if(hm.matches()){int h=Integer.parseInt(hm.group(1));active=closed.contains(h)?null:h;if(active!=null)by.put(active,new ArrayList<>());continue;}
          Matcher m=ROW.matcher(line.trim());
          if(active!=null && m.matches() && Integer.parseInt(m.group(1))==active)by.get(active).add(new String[]{m.group(2).trim(),m.group(3).trim()});
          else if(active!=null && line.trim().isEmpty() && !by.get(active).isEmpty()){closed.add(active);active=null;}
        }
        for(Map.Entry<Integer,List<String[]>> e:by.entrySet()){hands++;List<String>d=new ArrayList<>();for(String[] z:e.getValue()){String r=z[0],c=z[1];if(r.equalsIgnoreCase("DEALER upcard")||r.equalsIgnoreCase("DEALER hole card"))d.add(c);else if(r.toUpperCase(Locale.ROOT).startsWith("DEALER DRAW")){if(d.size()>=2&&total(d)>=17){findings.add(p.getFileName()+" | H"+e.getKey()+" | dealer already terminal "+total(d)+" | post-terminal gameplay card "+c);break;}d.add(c);}}}
      }
    }
    System.out.println("UNIVERSAL TERMINAL CHRONOLOGY AUDIT");
    System.out.println("Files scanned: "+files+" | hands scanned: "+hands+" | violations: "+findings.size());
    for(String f:findings)System.out.println("FAIL | "+f);
    if(findings.isEmpty()){System.out.println("UNIVERSAL TERMINAL CHRONOLOGY AUDIT: PASS");System.exit(0);}else{System.out.println("UNIVERSAL TERMINAL CHRONOLOGY AUDIT: REVIEW REQUIRED — retained evidence is not rewritten automatically");System.exit(2);}
  }
}
