/**
 * CoffeeOrderBot - State machine for ordering coffee
 * This example demonstrates how to implement a finite state machine
 * to manage the flow of a conversation.
 *
 * Part of Part III of the book "Introduction to Programming in Java"
 */

import java.util.*;

public class CoffeeOrderBot {

    // State definitions
    public enum State {
        INIT,          // Initial state
        CHOOSE_COFFEE, // Choosing the coffee type
        CHOOSE_SIZE,   // Choosing the size
        CHOOSE_MILK,   // Choosing whether to add milk
        CONFIRM,       // Confirming the order
        COMPLETE       // Order complete
    }

    // Event type definitions (user messages)
    public enum Event {
        START_ORDER,
        SELECT_COFFEE,
        SELECT_SIZE,
        SELECT_MILK,
        CONFIRM,
        CANCEL,
        UNKNOWN
    }

    // Current bot state
    private State currentState;

    // Order data
    private String coffeeType;
    private String size;
    private boolean withMilk;

    // Transition rules: (current state, event) -> response template
    private static final Map<State, Map<Event, String>> TRANSITION_RULES = new EnumMap<>(State.class);

    static {
        // Rules for the INIT state
        Map<Event, String> initRules = new EnumMap<>(Event.class);
        initRules.put(Event.START_ORDER, "Okay, what kind of coffee would you like? (Espresso, Latte, Cappuccino)");
        TRANSITION_RULES.put(State.INIT, initRules);

        // Rules for the CHOOSE_COFFEE state
        Map<Event, String> coffeeRules = new EnumMap<>(Event.class);
        coffeeRules.put(Event.SELECT_COFFEE, "Got it! Now, what size? (Small, Medium, Large)");
        TRANSITION_RULES.put(State.CHOOSE_COFFEE, coffeeRules);

        // Rules for the CHOOSE_SIZE state
        Map<Event, String> sizeRules = new EnumMap<>(Event.class);
        sizeRules.put(Event.SELECT_SIZE, "With milk or without milk? (With, Without)");
        TRANSITION_RULES.put(State.CHOOSE_SIZE, sizeRules);

        // Rules for the CHOOSE_MILK state
        Map<Event, String> milkRules = new EnumMap<>(Event.class);
        milkRules.put(Event.SELECT_MILK, "Please confirm: {1} {0}, {2}. (Yes, No)");
        TRANSITION_RULES.put(State.CHOOSE_MILK, milkRules);

        // Rules for the CONFIRM state
        Map<Event, String> confirmRules = new EnumMap<>(Event.class);
        confirmRules.put(Event.CONFIRM, "Perfect! Your coffee is being prepared.");
        confirmRules.put(Event.CANCEL, "Order canceled.");
        TRANSITION_RULES.put(State.CONFIRM, confirmRules);
    }

    public CoffeeOrderBot() {
        currentState = State.INIT;
        resetOrder();
    }

    private void resetOrder() {
        coffeeType = null;
        size = null;
        withMilk = false;
    }

    /**
     * Classifies the user's message into an event.
     * @param message The user's message
     * @return The corresponding event
     */
    private Event classifyEvent(String message) {
        message = message.toLowerCase().trim();

        switch (currentState) {
            case INIT:
            case COMPLETE:
                if (message.contains("coffee") || message.contains("buy") || message.contains("order")) {
                    return Event.START_ORDER;
                }
                break;

            case CHOOSE_COFFEE:
                if (message.contains("espresso")) return Event.SELECT_COFFEE;
                if (message.contains("latte")) return Event.SELECT_COFFEE;
                if (message.contains("cappuccino")) return Event.SELECT_COFFEE;
                break;

            case CHOOSE_SIZE:
                if (message.contains("small")) return Event.SELECT_SIZE;
                if (message.contains("medium")) return Event.SELECT_SIZE;
                if (message.contains("large")) return Event.SELECT_SIZE;
                break;

            case CHOOSE_MILK:
                if (message.contains("without") || message.contains("no")) return Event.SELECT_MILK;
                if (message.contains("with") || message.contains("yes")) return Event.SELECT_MILK;
                break;

            case CONFIRM:
                if (message.contains("yes") || message.contains("ok") || message.contains("confirm")) return Event.CONFIRM;
                if (message.contains("no") || message.contains("cancel")) return Event.CANCEL;
                if (message.contains("coffee") || message.contains("buy") || message.contains("order")) {
                    return Event.START_ORDER;
                }
                break;
        }

        return Event.UNKNOWN;
    }

    /**
     * Processes the message and updates the state.
     * @param message The user's message
     * @return The bot's response
     */
    public String process(String message) {
        Event event = classifyEvent(message);

        // Update order data based on the event
        switch (currentState) {
            case CHOOSE_COFFEE:
                if (event == Event.SELECT_COFFEE) {
                    coffeeType = message.trim();
                }
                break;

            case CHOOSE_SIZE:
                if (event == Event.SELECT_SIZE) {
                    size = message.trim();
                }
                break;

            case CHOOSE_MILK:
                if (event == Event.SELECT_MILK) {
                    String lower = message.toLowerCase();
                    withMilk = !lower.contains("without") && !lower.contains("no")
                            && (lower.contains("with") || lower.contains("yes"));
                }
                break;
        }

        // Apply transition rules
        Map<Event, String> stateRules = TRANSITION_RULES.get(currentState);
        if (stateRules != null && stateRules.containsKey(event)) {
            String response = stateRules.get(event);

            // Format the confirmation message
            if (currentState == State.CHOOSE_MILK && event == Event.SELECT_MILK) {
                String milkText = withMilk ? "with milk" : "without milk";
                response = response.replace("{0}", coffeeType)
                                   .replace("{1}", size)
                                   .replace("{2}", milkText);
            }

            // Update the state
            switch (currentState) {
                case INIT:
                    if (event == Event.START_ORDER) currentState = State.CHOOSE_COFFEE;
                    break;

                case CHOOSE_COFFEE:
                    if (event == Event.SELECT_COFFEE) currentState = State.CHOOSE_SIZE;
                    break;

                case CHOOSE_SIZE:
                    if (event == Event.SELECT_SIZE) currentState = State.CHOOSE_MILK;
                    break;

                case CHOOSE_MILK:
                    if (event == Event.SELECT_MILK) currentState = State.CONFIRM;
                    break;

                case CONFIRM:
                    if (event == Event.CONFIRM) currentState = State.COMPLETE;
                    if (event == Event.CANCEL) currentState = State.INIT;
                    break;

                case COMPLETE:
                    if (event == Event.START_ORDER) {
                        currentState = State.CHOOSE_COFFEE;
                        resetOrder();
                    }
                    break;
            }

            return response;
        }

        // Handle starting a new order from CONFIRM or COMPLETE
        switch (currentState) {
            case CONFIRM:
            case COMPLETE:
                if (event == Event.START_ORDER) {
                    currentState = State.CHOOSE_COFFEE;
                    resetOrder();
                    return "Okay, starting a new order. What kind of coffee would you like? (Espresso, Latte, Cappuccino)";
                }
                break;
        }

        return "I didn't understand. Could you repeat that or enter a valid option?";
    }

    public State getCurrentState() {
        return currentState;
    }

    public static void main(String[] args) {
        CoffeeOrderBot bot = new CoffeeOrderBot();
        Scanner scanner = new Scanner(System.in);

        System.out.println("Coffee Order Bot. Type 'exit' to quit.");

        while (true) {
            System.out.print("User: ");
            String input = scanner.nextLine();

            if (input.equalsIgnoreCase("exit")) {
                break;
            }

            String response = bot.process(input);
            System.out.println("Bot: " + response);

            if (bot.getCurrentState() == State.COMPLETE) {
                System.out.println("Order complete! Type 'order' to start a new order.");
            }
        }

        scanner.close();
    }
}
