<%-----build strucutre check-----%>
<%@ page import="java.io.*, java.util.*, java.security.*" %>
<%@ page import="com.google.gson.Gson" %>
<%@ include file="utils.jspf" %>


<%!
    class ExtraInfo {
        String appName;
        String version;
        String platform;

        ExtraInfo(Properties prop) {
            this.appName = prop.getProperty("app.name");
            this.version = prop.getProperty("app.version");
            this.platform = prop.getProperty("app.platform");
        }
    }
    class BuildInfo {
        String status;
        Map<String, String> errors;
        Map<String, String> warnings;
        List<String> resolutions;
        ExtraInfo extraInfo;

        BuildInfo(Properties prop, Map<String, Object> directories) {
            this.errors = new HashMap<>();
            this.warnings = new HashMap<>();
            this.resolutions = new ArrayList<>();
            this.extraInfo = new ExtraInfo(prop);

            boolean isValid = (boolean) directories.get("isValid");
            this.status = isValid ? "pass" : "fail";

            if (!isValid) {
                Map<String, String> details = (Map<String, String>) directories.get("details");
                List<String> resolutions = (List<String>) directories.get("resolutions");
                this.errors.putAll(details);
                this.resolutions.addAll(resolutions);
            }
        }
    }

    public Map<String, Object> validateVersionDirectory(ServletContext application, String version, Properties prop) {
        Map<String, String> validationErrors = new LinkedHashMap<>();
        Set<String> validationResolutions = new LinkedHashSet<>();
        boolean isValid = true;

        for (String key : prop.stringPropertyNames()) {
            if (key.startsWith("validate.") && key.endsWith(".directories")) {
                String directoryPath = getRealPath(application, prop.getProperty(key));
                String directoryName = key.substring(key.lastIndexOf("validate.") + 9, key.lastIndexOf(".directories"));
                File directory = new File(directoryPath);

                // Check if directory exists and is valid
                if (!directory.exists() || !directory.isDirectory()) {
                    validationErrors.put(prop.getProperty(key), "E: Invalid path or directory does not exist.");
                    validationResolutions.add(resolutionMessages.getOrDefault("E01", "Please Redeploy Plugin"));
                    isValid = false;
                    continue;
                }

                // Get subdirectories
                File[] subdirectories = directory.listFiles(File::isDirectory);
                if (subdirectories == null || subdirectories.length == 0) {
                    validationErrors.put(prop.getProperty(key), "E: No subdirectories found in " + directoryName + ".");
                    validationResolutions.add(resolutionMessages.getOrDefault("E01", "Please Redeploy Plugin"));
                    isValid = false;
                    continue;
                }

                // Validate version folder structure
                File matchedDir = null;
                int count = 0;

                for (File subDir : subdirectories) {
                    if (subDir.getName().startsWith("v")) {
                        count++;
                        matchedDir = subDir;
                    }
                }

                if (count > 1) {
                    validationErrors.put(prop.getProperty(key), "E: Multiple version directories found inside " + directoryName);
                    validationResolutions.add(resolutionMessages.getOrDefault("E02", "Please Redeploy Plugin"));
                    isValid = false;
                    continue;
                }

                if (matchedDir == null) {
                    validationErrors.put(prop.getProperty(key), "E: No directory found starting with 'v'.");
                    validationResolutions.add(resolutionMessages.getOrDefault("E01", "Please Redeploy Plugin"));
                    isValid = false;
                    continue;
                }

                // Validate version match
                String foundVersion = matchedDir.getName().substring(1); // Remove "v" prefix
                if (!foundVersion.equals(version)) {
                    validationErrors.put(prop.getProperty(key), "E: Expected 'v" + version + "', but found 'v" + foundVersion + "'.");
                    validationResolutions.add(resolutionMessages.getOrDefault("E03", "Please Redeploy Plugin"));
                    isValid = false;
                }
            }
        }

        // Return stuructured result: Only return details if something is wrong
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("isValid", isValid);
        if (!isValid) {
            result.put("details", validationErrors);
            result.put("resolutions", new ArrayList<>(validationResolutions));
        }
        return result;
    }
%>

<% 
    Properties prop = readStateProperties(getRealPath(application, "VitaraCharts/utils/CheckHealth/state.properties"));
    String appVersion = prop.getProperty("app.version");

    //validating directories 
    Map<String, Object> validateResults = validateVersionDirectory(application, appVersion, prop);

    BuildInfo build = new BuildInfo(prop, validateResults);
    Gson gson = new Gson();
    String json = gson.toJson(build);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    out.print(json);
    out.flush();
%>
