package de.oaa.libredeck.web.service;

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

public final class TrackNormalizer {

    private static final Pattern FEAT_PARENS = Pattern.compile(
            "\\s*[\\(\\[]\\s*(?:feat\\.?|ft\\.?|featuring|with)\\s+([^\\)\\]]+)[\\)\\]]",
            Pattern.CASE_INSENSITIVE);
    private static final Pattern FEAT_DASH = Pattern.compile(
            "\\s*[-–]\\s*(?:feat\\.?|ft\\.?|featuring)\\s+(.+)$",
            Pattern.CASE_INSENSITIVE);

    private static final String ANNOTATION_KEYWORDS =
            "remaster(ed)?|album version|single version|radio edit|radio version|" +
            "extended version|original version|soundtrack|from\\b|" +
            "official|live|hd|hq|4k|upgrade|with\\s+lyrics|lyrics?|promo|music\\s+video|lyric\\s+video|version";

    private static final Pattern ANNOTATION_PARENS = Pattern.compile(
            "\\s*[\\(\\[][^\\)\\]]*\\b(?:" + ANNOTATION_KEYWORDS + ")[^\\)\\]]*[\\)\\]]",
            Pattern.CASE_INSENSITIVE);
    private static final Pattern ANNOTATION_DASH = Pattern.compile(
            "\\s*[-–]\\s*[^(\\[]*?\\b(?:" + ANNOTATION_KEYWORDS + ").*$",
            Pattern.CASE_INSENSITIVE);
    // *annotation text* style (e.g. "*in the description box*")
    private static final Pattern ANNOTATION_ASTERISK = Pattern.compile(
            "\\s*\\*[^*]+\\*", Pattern.CASE_INSENSITIVE);
    // trailing resolution tokens like "WIDESCREEN 720p", "720p", "1080p"
    private static final Pattern RESOLUTION_SUFFIX = Pattern.compile(
            "\\s+(?:WIDESCREEN\\s+)?\\d{3,4}p$", Pattern.CASE_INSENSITIVE);

    private TrackNormalizer() {}

    public static String cleanTitle(String title) {
        title = ANNOTATION_ASTERISK.matcher(title).replaceAll("");
        title = ANNOTATION_PARENS.matcher(title).replaceAll("");
        title = ANNOTATION_DASH.matcher(title).replaceAll("");
        title = RESOLUTION_SUFFIX.matcher(title).replaceAll("");
        return title.trim();
    }

    /** Moves feat./ft./featuring info from the title into the artist string. */
    public static String[] extractFeaturing(String title, String artist) {
        Matcher m = FEAT_PARENS.matcher(title);
        if (!m.find()) m = FEAT_DASH.matcher(title);
        if (!m.find()) return new String[]{title, artist};

        String featArtist   = m.group(1).trim();
        String cleanedTitle = m.replaceAll("").trim();

        if (!artist.toLowerCase().contains(featArtist.toLowerCase())) {
            artist = artist + " feat. " + featArtist;
        }
        return new String[]{cleanedTitle, artist};
    }
}
