import java.util.ArrayList;
import java.util.List;

/**
 * La regla de nuestro CSV: campos separados por comas; un campo que tiene una
 * coma o comillas va entre comillas, y sus comillas se escriben dobles.
 * No se permiten saltos de línea dentro de un campo.
 */
public final class Csv {
    private Csv() {
    }

    public static String join(List<String> fields) {
        List<String> quoted = new ArrayList<>();
        for (String f : fields) {
            if (f.contains("\n") || f.contains("\r")) {
                throw new IllegalArgumentException("salto de línea en un campo: " + f);
            }
            if (f.contains(",") || f.contains("\"")) {
                quoted.add("\"" + f.replace("\"", "\"\"") + "\"");
            } else {
                quoted.add(f);
            }
        }
        return String.join(",", quoted);
    }

    /** Parte una línea en campos. Lanza IllegalArgumentException si las comillas no cierran. */
    public static List<String> split(String line) {
        List<String> fields = new ArrayList<>();
        StringBuilder current = new StringBuilder();
        boolean inQuotes = false;
        for (int i = 0; i < line.length(); i++) {
            char c = line.charAt(i);
            if (inQuotes) {
                if (c == '"' && i + 1 < line.length() && line.charAt(i + 1) == '"') {
                    current.append('"');
                    i++;
                } else if (c == '"') {
                    inQuotes = false;
                } else {
                    current.append(c);
                }
            } else if (c == '"') {
                inQuotes = true;
            } else if (c == ',') {
                fields.add(current.toString());
                current.setLength(0);
            } else {
                current.append(c);
            }
        }
        if (inQuotes) {
            throw new IllegalArgumentException("comillas sin cerrar");
        }
        fields.add(current.toString());
        return fields;
    }
}
