package edu.caltech.cs2.project02.guessers;

import edu.caltech.cs2.project02.interfaces.IHangmanGuesser;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class AIHangmanGuesser implements IHangmanGuesser {
    private static final String dictName = "scrabble.txt";
    @Override
    public char getGuess(String pattern, Set<Character> guesses) throws FileNotFoundException {
        // 1. load all words from data/scrabble.txt into dictionary
        ArrayList<String> dict = new ArrayList<>(); // contains separate, distinct words
        try {
            File obj = new File("data/" + dictName);
            Scanner scanner = new Scanner(obj);
            while (scanner.hasNextLine()) {
                String nextLine = scanner.nextLine();
                dict.add(nextLine);
            }
            scanner.close();
        }
        catch (FileNotFoundException e) {
            System.out.println("The specified file wasn't found.");
            e.printStackTrace();
        }

        // 2. loop through dict to find words that match pattern
        SortedSet<String> matches = new TreeSet<>();
        for (String word : dict) {
            if ((!guesses.contains(word)) && (word.length() == pattern.length())) {
                for (int i = 0; i < pattern.length(); i++) {
                    char p = pattern.charAt(i);
                    char w = word.charAt(i);

//                    if ((p != '-') && (p != w))
//                        break;
//                    else if ((p == '-') && (pattern.contains(Character.toString(w)))) {
//                        break;
//                    }

                    // this is the same thing as the commented code above
                    if (((p != '-') && (p == w)) || ((p == '-') && (!pattern.contains(Character.toString(w)))))
                        matches.add(word);
                }
            }
        }

        // 3. create TreeMap with letter : freq
        TreeMap<Character, Integer> freqs = new TreeMap<>();
        for (String word : matches) {
            for (int i = 0; i < word.length(); i++) {
                char letter = word.charAt(i);
                if (!freqs.containsKey(letter)) {
                    freqs.put(letter, 1);
                }
                else {
                    freqs.put(letter, freqs.get(letter) + 1);
                }
            }
        }

        // 4. find letter in TreeMap with highest freq
        int bestFreq = 0;
        char bestLetter = 'a';
        for (char c = 'a'; c <= 'z'; c++) {
            // no need to check if the bestFreq ties,
            // because we're already iterating through alphabetical order
            if ((freqs.containsKey(c)) && (freqs.get(c) > bestFreq)) {
                bestFreq = freqs.get(c);
                bestLetter = c;
            }
        }
        return bestLetter;
    }
}
