import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;

public final class TransactionRetryDemo {
    public static void main(String[] args) throws Exception {
        if (args.length != 3) {
            throw new IllegalArgumentException("Usage: TransactionRetryDemo from to amount");
        }
        long from = Long.parseLong(args[0]);
        long to = Long.parseLong(args[1]);
        int amount = Integer.parseInt(args[2]);
        if (from == to || amount <= 0) {
            throw new IllegalArgumentException("Distinct accounts and positive amount required");
        }
        String url = required("DB_URL");
        String user = required("DB_USER");
        String password = required("DB_PASSWORD");
        long deadline = System.nanoTime() + Duration.ofSeconds(15).toNanos();
        for (int attempt = 1; attempt <= 3; attempt++) {
            ensureBudget(deadline);
            SQLException retryFailure;
            try (Connection connection = DriverManager.getConnection(url, user, password)) {
                connection.setAutoCommit(false);
                boolean commitStarted = false;
                try {
                    try (PreparedStatement setting = connection.prepareStatement(
                            "SET SESSION innodb_lock_wait_timeout=2")) {
                        setting.setQueryTimeout(timeoutSeconds(deadline));
                        setting.execute();
                    }
                    lockAccount(connection, Math.min(from, to), deadline);
                    lockAccount(connection, Math.max(from, to), deadline);
                    try (PreparedStatement debit = connection.prepareStatement(
                            "UPDATE deadlock_account SET balance=balance-? WHERE id=? AND balance>=?")) {
                        debit.setInt(1, amount);
                        debit.setLong(2, from);
                        debit.setInt(3, amount);
                        debit.setQueryTimeout(timeoutSeconds(deadline));
                        if (debit.executeUpdate() != 1) {
                            throw new SQLException("Insufficient balance", "45000");
                        }
                    }
                    try (PreparedStatement credit = connection.prepareStatement(
                            "UPDATE deadlock_account SET balance=balance+? WHERE id=?")) {
                        credit.setInt(1, amount);
                        credit.setLong(2, to);
                        credit.setQueryTimeout(timeoutSeconds(deadline));
                        if (credit.executeUpdate() != 1) {
                            throw new SQLException("Credit failed", "45000");
                        }
                    }
                    ensureBudget(deadline);
                    commitStarted = true;
                    connection.commit();
                    System.out.println("commit-confirmed attempt=" + attempt);
                    return;
                } catch (SQLException failure) {
                    if (commitStarted) {
                        throw new SQLException("Commit outcome requires reconciliation; do not retry", "08007", failure);
                    }
                    try {
                        connection.rollback();
                    } catch (SQLException rollbackFailure) {
                        failure.addSuppressed(rollbackFailure);
                        throw failure;
                    }
                    System.err.println("rollback-confirmed attempt=" + attempt
                            + " code=" + failure.getErrorCode() + " state=" + failure.getSQLState());
                    if (!retryable(failure) || attempt == 3) {
                        throw failure;
                    }
                    retryFailure = failure;
                }
            }
            long pauseMillis = ThreadLocalRandom.current().nextLong(20L * attempt + 1);
            if (deadline - System.nanoTime() <= Duration.ofMillis(pauseMillis).toNanos()) {
                throw new SQLException("Retry budget exhausted", "HYT00", retryFailure);
            }
            try {
                Thread.sleep(pauseMillis);
            } catch (InterruptedException interrupted) {
                Thread.currentThread().interrupt();
                throw interrupted;
            }
        }
    }

    private static void lockAccount(Connection connection, long account, long deadline) throws SQLException {
        try (PreparedStatement statement = connection.prepareStatement(
                "SELECT id FROM deadlock_account WHERE id=? FOR UPDATE")) {
            statement.setLong(1, account);
            statement.setQueryTimeout(timeoutSeconds(deadline));
            try (ResultSet result = statement.executeQuery()) {
                if (!result.next()) {
                    throw new SQLException("Account not found: " + account, "45000");
                }
            }
        }
    }

    private static boolean retryable(SQLException failure) {
        return (failure.getErrorCode() == 1213 && "40001".equals(failure.getSQLState()))
                || failure.getErrorCode() == 1205;
    }

    private static int timeoutSeconds(long deadline) throws SQLException {
        long remaining = deadline - System.nanoTime();
        if (remaining <= 0) {
            throw new SQLException("Operation budget exhausted", "HYT00");
        }
        return (int) Math.max(1, (remaining + 999_999_999L) / 1_000_000_000L);
    }

    private static void ensureBudget(long deadline) throws SQLException {
        timeoutSeconds(deadline);
    }

    private static String required(String name) {
        String value = System.getenv(name);
        if (value == null || value.isBlank()) {
            throw new IllegalArgumentException("Missing environment variable: " + name);
        }
        return value;
    }
}
