import java.sql.*;

public class MDEV40911Repro {
    public static void main(String[] args) throws Exception {
        String host = args.length > 0 ? args[0] : "127.0.0.1";
        String port = args.length > 1 ? args[1] : "3306";
        String db   = args.length > 2 ? args[2] : "test";

        String url = "jdbc:mariadb://" + host + ":" + port + "/" + db
                    + "?useUnicode=true&characterEncoding=UTF-8&useServerPrepStmts=true";

        System.out.println("Connecting to: " + url);

        try (Connection conn = DriverManager.getConnection(url, "root", "")) {
            try (Statement s = conn.createStatement()) {

                s.execute("SET NAMES utf8mb4 COLLATE utf8mb4_uca1400_ai_ci");

                ResultSet rs0 = s.executeQuery(
                    "SELECT @@character_set_client, @@collation_connection");
                rs0.next();
                System.out.println("Before capture/restore sequence: client=" + rs0.getString(1)
                                  + " collation=" + rs0.getString(2));

                s.execute("SET @OLD_CHARACTER_SET_CLIENT = @@CHARACTER_SET_CLIENT");
                s.execute("SET @OLD_COLLATION_CONNECTION = @@COLLATION_CONNECTION");
                s.execute("SET NAMES utf8mb4");
                s.execute("SET CHARACTER_SET_CLIENT = @OLD_CHARACTER_SET_CLIENT");
                s.execute("SET COLLATION_CONNECTION = @OLD_COLLATION_CONNECTION");

                ResultSet rs1 = s.executeQuery(
                    "SELECT @@collation_connection, @@character_set_client");
                rs1.next();
                String afterCollation = rs1.getString(1);
                System.out.println("After capture/restore sequence: collation=" + afterCollation
                                  + " client=" + rs1.getString(2));

                try (PreparedStatement ps = conn.prepareStatement("SELECT COLLATION(?)")) {
                    ps.setString(1, "x");
                    ResultSet rs = ps.executeQuery();
                    rs.next();
                    String boundCollation = rs.getString(1);
                    System.out.println("Bound param collation: " + boundCollation);

                    System.out.println(boundCollation.equals(afterCollation)
                        ? "RESULT: OK -- no reproduction"
                        : "RESULT: BUG REPRODUCED -- mismatch!");
                }
            }
        }
    }
}
