/**
 * PhraseExtraction - Phrase extraction using capture groups
 * This example demonstrates how to extract important parts of a message
 * using regular expressions with capture groups.
 *
 * Part III of the book "Introduction to Programming in Java"
 */

import java.util.regex.*;

public class PhraseExtraction {

    private static final String BOT_TEMPLATE = "BOT: %s";
    private static final String USER_TEMPLATE = "USER: %s";

    public static void main(String[] args) {
        // Example 1: Extract what the user wants
        String message = "I want to learn how to build chatbots";
        Pattern pattern = Pattern.compile("I want (.*)");
        Matcher matcher = pattern.matcher(message);

        if (matcher.find()) {
            String phrase = matcher.group(1); // "to learn how to build chatbots"
            System.out.println(String.format(USER_TEMPLATE, message));
            System.out.println(String.format(BOT_TEMPLATE, "Why do you want " + phrase + "?"));
        }

        System.out.println();

        // Example 2: Extract what the user remembers
        message = "Do you remember the last time we coded together?";
        pattern = Pattern.compile("Do you remember (.*?)\\??$");
        matcher = pattern.matcher(message);

        if (matcher.find()) {
            String phrase = matcher.group(1);
            System.out.println(String.format(USER_TEMPLATE, message));
            System.out.println(String.format(BOT_TEMPLATE, "How could I forget " + phrase + "?"));
        }

        System.out.println();

        // Example 3: Extract from the middle of a sentence
        message = "If I study hard, I will pass the exam";
        pattern = Pattern.compile("If (.*),");
        matcher = pattern.matcher(message);

        if (matcher.find()) {
            String condition = matcher.group(1); // "I study hard"
            System.out.println(String.format(USER_TEMPLATE, message));
            System.out.println(String.format(BOT_TEMPLATE, "Do you think it's likely that " + condition + "?"));
        }
    }
}
