import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Scanner;

public class Chapter16Project {
    interface Command {
        String execute();
    }

    static final class CommandRegistry {
        private final Map<String, Command> commands = new LinkedHashMap<>();

        void register(String name, Command command) {
            String key = normalize(name);
            if (key.isBlank()) {
                throw new IllegalArgumentException("Command name is required.");
            }
            if (commands.putIfAbsent(key, command) != null) {
                throw new IllegalArgumentException("Duplicate command: " + key);
            }
        }

        String execute(String name) {
            Command command = commands.get(normalize(name));
            return command == null ? "Unknown command. Type help." : command.execute();
        }

        String listNames() {
            return String.join(", ", commands.keySet());
        }
    }

    static final class History {
        private final List<String> lines = new ArrayList<>();

        void record(String input, String response) {
            lines.add("USER: " + input.strip());
            lines.add("BOT: " + response);
        }

        String format() {
            return lines.isEmpty() ? "No history." : String.join(System.lineSeparator(), lines);
        }

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

        void save(Path file) throws IOException {
            Files.write(file, lines, StandardCharsets.UTF_8);
        }
    }

    static final class TutorJavaBot {
        private final CommandRegistry registry = new CommandRegistry();
        private final History history = new History();
        private boolean awaitingQuiz;

        TutorJavaBot() {
            registry.register("hi", () -> "Hello! I am TutorJavaBot.");
            registry.register("tip", () -> "Write a test before refactoring.");
            registry.register("quiz", () -> "Which component executes Java bytecode?");
            registry.register("help", () -> "Commands: " + registry.listNames()
                    + ", history, and exit.");
        }

        String process(String input) {
            String command = normalize(input);
            if (command.isBlank()) {
                return "Type a message.";
            }
            if (command.equals("history")) {
                return history.format();
            }

            String response;
            if (awaitingQuiz) {
                response = command.equals("jvm")
                        ? "Correct!"
                        : "Incorrect answer. The answer is JVM.";
                awaitingQuiz = false;
            } else {
                response = registry.execute(command);
                if (command.equals("quiz")) {
                    awaitingQuiz = true;
                }
            }

            history.record(input, response);
            return response;
        }

        int totalInteractions() {
            return history.totalInteractions();
        }

        void save(Path file) throws IOException {
            history.save(file);
        }
    }

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

    public static void main(String[] args) {
        TutorJavaBot bot = new TutorJavaBot();

        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println(bot.process("help"));
            while (true) {
                System.out.print("You: ");
                String input = scanner.nextLine();
                if (normalize(input).equals("exit")) {
                    break;
                }
                System.out.println("Bot: " + bot.process(input));
            }
        }

        try {
            bot.save(Path.of("history.txt"));
            System.out.println("History saved.");
        } catch (IOException error) {
            System.out.println("Could not save history.");
            System.err.println(error.getMessage());
        }

        System.out.println("Interactions: " + bot.totalInteractions());
    }
}
