import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class Chapter10Chatbot {
    private final String name;
    private final List<String> history = new ArrayList<>();

    public Chapter10Chatbot(String name) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("Name is required.");
        }
        this.name = name.strip();
    }

    static String normalize(String text) {
        return text == null ? "" : text.strip().toLowerCase(Locale.ROOT);
    }

    public String respond(String input) {
        String command = normalize(input);
        if (command.isBlank()) {
            return "Enter a message.";
        }
        if (command.equals("history")) {
            return history.isEmpty()
                    ? "No history."
                    : String.join(System.lineSeparator(), history);
        }

        String reply = switch (command) {
            case "hi" -> "Hello! I am " + name + ".";
            case "help" -> "Commands: hi, help, tip, history, and exit.";
            case "tip" -> "Compile and test after every small change.";
            default -> "I did not understand. Type help.";
        };

        history.add("USER: " + input.strip());
        history.add("BOT: " + reply);
        return reply;
    }

    public int totalInteractions() {
        return history.size() / 2;
    }

    public static void main(String[] args) {
        Chapter10Chatbot bot = new Chapter10Chatbot("TutorJavaBot");
        System.out.println(bot.respond("hi"));
        System.out.println(bot.respond("history"));
        System.out.println("Interactions: " + bot.totalInteractions());
    }
}
