"""Read matching-relevant metadata from an audio file, including the embedded
MusicBrainz recording MBID and ISRC when present (e.g. Picard-tagged files).

Returns a flat dict so the local scanner can upsert without knowing tag formats.
"""
from mutagen import File as MutagenFile

_MB_OWNER = "http://musicbrainz.org"


def _first(value):
    if value is None:
        return None
    if isinstance(value, list):
        return str(value[0]) if value else None
    return str(value)


def _mp4_freeform(raw, key):
    if key in raw:
        try:
            return _first([bytes(x).decode("utf-8", "ignore") for x in raw[key]])
        except Exception:
            return None
    return None


def read_track_tags(path):
    try:
        audio = MutagenFile(path)
    except Exception:
        return None
    if audio is None:
        return None

    duration_ms = None
    if audio.info and getattr(audio.info, "length", None):
        duration_ms = int(audio.info.length * 1000)

    # Easy view normalizes common keys across ID3/Vorbis/MP4.
    etags = {}
    try:
        easy = MutagenFile(path, easy=True)
        etags = easy.tags or {}
    except Exception:
        etags = {}

    def eget(key):
        try:
            return _first(etags.get(key))
        except Exception:
            return None

    title = eget("title")
    artist = eget("artist")
    album = eget("album")
    artist_values = etags.get("artist") if isinstance(etags.get("artist"), list) else None
    artists = ", ".join(str(a) for a in artist_values) if artist_values else artist
    isrc = eget("isrc")
    mbid = eget("musicbrainz_trackid")  # recording MBID

    raw = audio.tags
    if raw is not None:
        if mbid is None:
            try:  # ID3 stores the recording MBID in a UFID frame
                for frame in raw.getall("UFID"):
                    if getattr(frame, "owner", None) == _MB_OWNER:
                        mbid = frame.data.decode("ascii", "ignore")
                        break
            except Exception:
                pass
            mbid = mbid or _mp4_freeform(raw, "----:com.apple.iTunes:MusicBrainz Track Id")
        if isrc is None:
            isrc = _mp4_freeform(raw, "----:com.apple.iTunes:ISRC")

    return {
        "title": title,
        "artist": artist,
        "artists": artists or artist,
        "album": album,
        "duration_ms": duration_ms,
        "isrc": isrc or None,
        "mbid": mbid or None,
    }
