"""Komerční banka: the page embeds the rate list as JSON in WIDGETS_CONFIG.""" import json import re from datetime import date from app.models import ParsedRates from app.sources.base import make_rate WIDGET_MARKER = "KBExchangeRatesList" ITEMS_PATTERN = re.compile(r'"items":\s*(?=\[)') ISO_DATE_LENGTH = 10 def parse(document: str) -> ParsedRates: widget_start = document.find(WIDGET_MARKER) if widget_start == -1: raise ValueError("KB rate list widget not found") items_match = ITEMS_PATTERN.search(document, widget_start) if items_match is None: raise ValueError("KB rate list items not found") items, _ = json.JSONDecoder().raw_decode(document, items_match.end()) if not items: raise ValueError("KB rate list is empty") # The universal contract carries non-cash rates. A currency without them is not offered. rates = [ make_rate( # "curencyIso" is the real spelling used by the source currency=item["curencyIso"], amount=item["currencyUnit"], buy=item["nonCashBuy"], sell=item["nonCashSell"], ) for item in items if item["nonCashBuy"] and item["nonCashSell"] ] valid_date = date.fromisoformat(items[0]["validDate"][:ISO_DATE_LENGTH]) return ParsedRates(valid_date=valid_date, rates=rates)