/**
 * ResponseGenerator - Response generator for the final project
 *
 * Part of Part III of the book "Introduction to Programming in Java"
 */

package chatbot;

import java.util.*;
import java.util.regex.*;

/**
 * Generates responses based on intent and context.
 */
public class ResponseGenerator {

    private static final Random RANDOM = new Random();

    // Responses for each intent
    private static final Map<IntentClassifier.Intent, List<String>> INTENT_RESPONSES =
        new EnumMap<>(IntentClassifier.Intent.class);

    static {
        INTENT_RESPONSES.put(IntentClassifier.Intent.GREETING, Arrays.asList(
            "Hello! How can I help you today?",
            "Hi there! I'm here to help.",
            "Good day! What do you need?",
            "Hey! How can I assist you?"
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.GOODBYE, Arrays.asList(
            "See you later! Have a great day!",
            "Goodbye! Come back anytime!",
            "Take care! See you soon!",
            "Bye! Wishing you a wonderful day!"
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.THANKS, Arrays.asList(
            "You're welcome! Happy to help.",
            "No problem at all!",
            "My pleasure! That's what I'm here for.",
            "Glad I could help! Just let me know if you need anything else."
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.HELP, Arrays.asList(
            "I can help you search for restaurants, book a table, check the weather, and tell jokes. " +
            "Try asking something like: 'Find an Italian restaurant' or 'I want to book a table'.",
            "I'm a chatbot that can search restaurants, make table reservations, " +
            "give weather updates, and tell jokes. Try asking me a question!"
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.WEATHER, Arrays.asList(
            "Today is sunny with pleasant temperatures.",
            "The weather is great for going out!",
            "Weather forecast: sunny with a few clouds.",
            "It's sunny today, though it might rain tomorrow. Bring a jacket!"
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.JOKE, Arrays.asList(
            "Why do Java developers wear glasses? Because they don't C#! 😄",
            "What's a programmer's favorite data type? A boolean, because it's always true or false! 😂",
            "Why didn't the programmer leave the house? Because they hadn't made a commit yet! 🤣",
            "Why did the computer go to the doctor? Because it caught a virus! 😷"
        ));

        INTENT_RESPONSES.put(IntentClassifier.Intent.UNKNOWN, Arrays.asList(
            "Sorry, I didn't understand. Could you repeat that or be more specific?",
            "I'm not sure what you mean. Try typing 'help'.",
            "I don't seem to know how to answer that. Would you like me to call a human?",
            "Hmm, I didn't catch that. Could you rephrase?"
        ));
    }

    /**
     * Generates a random response for the given intent.
     * @param intent The message intent
     * @return A randomly selected response
     */
    public static String generateRandomResponse(IntentClassifier.Intent intent) {
        List<String> responses = INTENT_RESPONSES.get(intent);
        return responses.get(RANDOM.nextInt(responses.size()));
    }

    /**
     * Swaps first-person and second-person pronouns in a sentence.
     * @param text The sentence to transform
     * @return The sentence with pronouns swapped
     */
    public static String replacePronouns(String text) {
        Pattern pronounPattern = Pattern.compile("\\b(I|me|my|am|you|your|are)\\b", Pattern.CASE_INSENSITIVE);
        return pronounPattern.matcher(text).replaceAll(match -> {
            switch (match.group().toLowerCase()) {
                case "i":
                case "me":
                    return "you";
                case "my":
                    return "your";
                case "am":
                    return "are";
                case "you":
                    return "I";
                case "your":
                    return "my";
                case "are":
                    return "am";
                default:
                    return match.group();
            }
        });
    }

    /**
     * Formats restaurant search results.
     * @param results List of matching restaurants
     * @return Formatted message with the results
     */
    public static String formatRestaurantResults(List<Map<String, Object>> results) {
        if (results.isEmpty()) {
            return "Sorry, I couldn't find any restaurants matching those criteria.";
        } else if (results.size() == 1) {
            Map<String, Object> r = results.get(0);
            return String.format("I found 1 restaurant: %s (%s, %s, rating: %.1f★)",
                r.get("name"),
                r.get("price_range"),
                r.get("area"),
                r.get("rating"));
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append(String.format("I found %d restaurants:\n", results.size()));
            for (Map<String, Object> r : results) {
                sb.append(String.format("  - %s (%s, %.1f★)\n",
                    r.get("name"),
                    r.get("area"),
                    r.get("rating")));
            }
            return sb.toString();
        }
    }

    /**
     * Formats a reservation confirmation message.
     * @param context Context containing the reservation details
     * @return Formatted confirmation message
     */
    public static String formatBookingConfirmation(Map<String, String> context) {
        return String.format(
            "Reservation confirmed!\n" +
            "Restaurant: %s\n" +
            "Date: %s\n" +
            "Time: %s\n" +
            "People: %s\n" +
            "Thank you for using our service!",
            context.getOrDefault("restaurant", "?"),
            context.getOrDefault("date", "?"),
            context.getOrDefault("time", "?"),
            context.getOrDefault("people", "?")
        );
    }
}
