package com.foxx.androidcast.remoteaccess;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Parse wg-quick snippets used by TUN fallback. */
public final class WireGuardQuickConfig {
    private WireGuardQuickConfig() {}

    public static String parseAddress(String wgConfig) {
        if (wgConfig == null) {
            return null;
        }
        Matcher m = Pattern.compile("(?m)^Address\\s*=\\s*(.+)$").matcher(wgConfig);
        return m.find() ? m.group(1).trim() : null;
    }

    public static String[] parseAllowedRoutes(String wgConfig) {
        if (wgConfig == null) {
            return new String[0];
        }
        Matcher m = Pattern.compile("(?m)^AllowedIPs\\s*=\\s*(.+)$").matcher(wgConfig);
        if (!m.find()) {
            return new String[0];
        }
        String[] parts = m.group(1).trim().split("\\s*,\\s*");
        ArrayList<String> out = new ArrayList<>();
        for (String p : parts) {
            if (!p.isEmpty()) {
                out.add(p.trim());
            }
        }
        return out.toArray(new String[0]);
    }

    public static String[] parseIncludedApplications(String wgConfig) {
        if (wgConfig == null) {
            return new String[0];
        }
        Matcher m = Pattern.compile("(?m)^IncludedApplications\\s*=\\s*(.+)$").matcher(wgConfig);
        if (!m.find()) {
            return new String[0];
        }
        String[] parts = m.group(1).trim().split("\\s*,\\s*");
        ArrayList<String> out = new ArrayList<>();
        for (String p : parts) {
            if (!p.isEmpty()) {
                out.add(p.trim());
            }
        }
        return out.toArray(new String[0]);
    }
}
