package com.lemenzo.gallery.viewer;

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

/** Pure-Java parser for Motion Photo XMP metadata. Tail bytes must still be verified as MP4. */
public final class MotionPhotoXmpParser {
    private static final Pattern ITEM_TAG = Pattern.compile("<(?:Container|GContainer):Item\\b[^>]*>", Pattern.CASE_INSENSITIVE);
    private static final Pattern MIME = Pattern.compile("(?:Item|GContainerItem):Mime=\\\"([^\\\"]+)\\\"", Pattern.CASE_INSENSITIVE);
    private static final Pattern LENGTH = Pattern.compile("(?:Item|GContainerItem):Length=\\\"(\\d+)\\\"", Pattern.CASE_INSENSITIVE);
    private static final Pattern MICRO_OFFSET = Pattern.compile("(?:Camera|GCamera):MicroVideoOffset=\\\"(\\d+)\\\"", Pattern.CASE_INSENSITIVE);
    private static final Pattern MOTION_FLAG = Pattern.compile("(?:Camera|GCamera):(?:MotionPhoto|MicroVideo)=\\\"1\\\"", Pattern.CASE_INSENSITIVE);
    private MotionPhotoXmpParser() {}

    public static long candidateVideoLength(String xmp) {
        if (xmp == null || xmp.isEmpty() || !MOTION_FLAG.matcher(xmp).find()) return 0L;
        Matcher tags = ITEM_TAG.matcher(xmp);
        while (tags.find()) {
            String tag = tags.group(); Matcher mime = MIME.matcher(tag); Matcher length = LENGTH.matcher(tag);
            if (mime.find() && "video/mp4".equalsIgnoreCase(mime.group(1)) && length.find()) {
                try { return Long.parseLong(length.group(1)); } catch (NumberFormatException ignored) { return 0L; }
            }
        }
        Matcher legacy = MICRO_OFFSET.matcher(xmp);
        if (legacy.find()) try { return Long.parseLong(legacy.group(1)); } catch (NumberFormatException ignored) { }
        return 0L;
    }
}
