"""MusicBrainz-Matching — Phase 5.""" import httpx from .base import MatchResult MB_BASE = "https://musicbrainz.org/ws/2" HEADERS = {"User-Agent": "audiolib/1.0 (https://github.com/audiolib)"} async def search_musicbrainz(title: str, artist: str | None = None) -> list[MatchResult]: query = f'release:"{title}"' if artist: query += f' AND artist:"{artist}"' query += " AND format:Digital" async with httpx.AsyncClient(headers=HEADERS, timeout=10) as client: resp = await client.get( f"{MB_BASE}/release", params={"query": query, "fmt": "json", "limit": 5}, ) resp.raise_for_status() data = resp.json() results = [] for release in data.get("releases", []): confidence = release.get("score", 0) / 100.0 artist_name = None credits = release.get("artist-credit", []) if credits: artist_name = credits[0].get("name") or credits[0].get("artist", {}).get("name") results.append( MatchResult( source="musicbrainz", source_id=release.get("id", ""), title=release.get("title", title), author=artist_name, confidence=confidence, ) ) return results