001/************************ PROJECT ZIXI ************************/
002/* Copyright (c) 2026 StuyPulse Robotics. All rights reserved.*/
003/* This work is licensed under the terms of the MIT license.  */
004/**************************************************************/
005package com.stuypulse.robot.util.auton;
006
007import org.wpilib.driverstation.DriverStationErrors;
008import org.wpilib.system.Filesystem;
009
010import java.io.File;
011import java.io.IOException;
012import java.nio.file.DirectoryStream;
013import java.nio.file.Files;
014import java.nio.file.Path;
015import java.util.ArrayList;
016import java.util.Collections;
017import java.util.HashMap;
018import java.util.List;
019
020/**
021 *
022 *
023 * <h2>AutonUtil</h2>
024 *
025 * Shared utilities for discovering and comparing autonomous path names.
026 */
027public final class AutonUtil {
028    private AutonUtil() {
029        throw new UnsupportedOperationException(
030                "This is a utility class and cannot be instantiated");
031    }
032
033    /** Represents a supported autonomous path format and its location in the deploy directory. */
034    public enum AutonType {
035        PATHPLANNER("pathplanner/paths", "path"),
036        BLINE("bline/autos/paths", "json");
037
038        private final String directory;
039        private final String extension;
040
041        private AutonType(String directory, String extension) {
042            this.directory = directory;
043            this.extension = extension;
044        }
045
046        /**
047         * Gets the path directory relative to the deploy directory.
048         *
049         * @return The path directory relative to the deploy directory
050         */
051        public String getDirectory() {
052            return directory;
053        }
054
055        /**
056         * Gets the file extension used by this autonomous format, without a leading dot.
057         *
058         * @return The file extension used by this autonomous format, without a leading dot
059         */
060        public String getExtension() {
061            return extension;
062        }
063    }
064
065    /**
066     * Lists the available path names for an autonomous format.
067     *
068     * @param autonType The auton type to search for determining which auton directory and file
069     *     extension to search
070     * @return Sorted path names without their file extensions. Returns an empty list if the
071     *     directory cannot be read, in which case an error is reported to the Driver Station
072     */
073    public static List<String> getPathFileNames(AutonType autonType) {
074        File pathsDir = new File(Filesystem.getDeployDirectory(), autonType.getDirectory());
075
076        ArrayList<String> fileList = new ArrayList<>();
077        try (DirectoryStream<Path> stream =
078                Files.newDirectoryStream(pathsDir.toPath(), "*." + autonType.getExtension())) {
079            for (Path file : stream) {
080                fileList.add(
081                        file.getFileName()
082                                .toString()
083                                .replaceFirst("." + autonType.getExtension(), ""));
084            }
085        } catch (IOException err) {
086            DriverStationErrors.reportError(err.getMessage(), false);
087        }
088        Collections.sort(fileList);
089        return fileList;
090    }
091
092    /**
093     * Finds the listed path name with the smallest character-based distance from an input.
094     *
095     * @param paths The possible path names to compare
096     * @param input The path name to match
097     * @return The closest candidate, or an empty string when no candidate is selected
098     */
099    public static String findClosestMatch(List<String> paths, String input) {
100        double closestValue = 10.0;
101        String matching = "";
102
103        for (String fileName : paths) {
104            HashMap<Character, Integer> fileChars = countChars(fileName.toCharArray());
105            HashMap<Character, Integer> inputChars = countChars(input.toCharArray());
106
107            double proximity = compareNameProximity(fileChars, inputChars);
108            closestValue = Math.min(proximity, closestValue);
109
110            if (proximity == closestValue) {
111                matching = fileName;
112            }
113        }
114
115        return matching;
116    }
117
118    /**
119     * Counts the occurrences of each character in an array.
120     *
121     * <p>This is mainly used for {@link #findClosestMatch(List, String)}.
122     *
123     * @param chars Characters to count
124     * @return A map from each encountered character to its amount of occurences
125     */
126    public static HashMap<Character, Integer> countChars(char[] chars) {
127        HashMap<Character, Integer> letterMap = new HashMap<>();
128        for (char i = 'a'; i <= 'z'; i++) letterMap.put(i, 0);
129        for (char i = 'a'; i <= 'z'; i++) letterMap.put(i, 0);
130        letterMap.put('(', 0);
131        letterMap.put(' ', 0);
132        letterMap.put(')', 0);
133        for (char letter : chars) {
134            if (letterMap.containsKey(letter)) {
135                letterMap.put(letter, letterMap.get(letter));
136            } else {
137                letterMap.put(letter, 1);
138            }
139        }
140        return letterMap;
141    }
142
143    /**
144     * Computes a character-count distance between two names.
145     *
146     * <p>Smaller values indicate closer names, while larger values indicate more distant names.
147     *
148     * <p>This is mainly used for {@link #findClosestMatch(List, String)}.
149     *
150     * @param list1 Character counts for the first name
151     * @param list2 Character counts for the second name
152     * @return The calculated distance between the names
153     */
154    public static double compareNameProximity(
155            HashMap<Character, Integer> list1, HashMap<Character, Integer> list2) {
156        double proximity = 0.0;
157        int list1sum = 0, list2sum = 0;
158        for (char key : list1.keySet()) {
159            if (!list2.containsKey(key)) {
160                proximity += 0.1;
161                continue;
162            }
163            proximity += 0.05 * Math.abs(list1.get(key) - list2.get(key));
164        }
165        for (char key : list2.keySet()) {
166            if (!list1.containsKey(key)) {
167                proximity += 0.1;
168                continue;
169            }
170            proximity += 0.05 * Math.abs(list1.get(key) - list2.get(key));
171        }
172        for (int count : list1.values()) list1sum += count;
173        for (int count : list2.values()) list2sum += count;
174        proximity += 0.4 * Math.abs(list2sum - list1sum);
175        return proximity;
176    }
177}