import httpx from .base import MatchResult GB_BASE = "https://www.googleapis.com/books/v1" async def search_google_books(title: str, author: str | None = None) -> list[MatchResult]: q = f'intitle:"{title}"' if author: q += f' inauthor:"{author}"' async with httpx.AsyncClient(timeout=12) as client: try: r = await client.get( f"{GB_BASE}/volumes", params={"q": q, "maxResults": 5, "langRestrict": "de", "printType": "books"}, ) r.raise_for_status() data = r.json() except Exception: return [] results = [] for item in data.get("items", []): vol = item.get("volumeInfo", {}) authors = vol.get("authors", []) cover_url = None image_links = vol.get("imageLinks", {}) if image_links: cover_url = ( image_links.get("extraLarge") or image_links.get("large") or image_links.get("medium") or image_links.get("thumbnail", "").replace("zoom=1", "zoom=3") ) year = None pub_date = vol.get("publishedDate", "") if pub_date and len(pub_date) >= 4: try: year = int(pub_date[:4]) except ValueError: pass results.append(MatchResult( source="google_books", source_id=item.get("id", ""), title=vol.get("title", title), subtitle=vol.get("subtitle"), author=authors[0] if authors else None, description=vol.get("description"), publisher=vol.get("publisher"), publish_year=year, language=vol.get("language"), genres=vol.get("categories", []), cover_url=cover_url, confidence=0.5, )) return results