"""J&T Banka: the page embeds the rates as escaped JSON objects in its page data.""" import json import re from datetime import date from app.models import ParsedRates from app.sources.base import make_rate ESCAPED_RATE_PATTERN = re.compile(r'\{\\"currency\\":\\"[A-Z]{3}\\".*?\}') ISO_DATE_LENGTH = 10 def parse(document: str) -> ParsedRates: # The same list can be embedded repeatedly, the first occurrence of a currency wins. items: dict[str, dict] = {} for match in ESCAPED_RATE_PATTERN.finditer(document): item = json.loads(match.group().replace('\\"', '"')) items.setdefault(item["currency"], item) if not items: raise ValueError("J&T rate list not found") # The universal contract carries non-cash rates. A currency without them is not offered. rates = [ make_rate( currency=currency, amount=item["unitAmount"], buy=item["nonCashBuy"], sell=item["nonCashSell"], ) for currency, item in items.items() if item["nonCashBuy"] and item["nonCashSell"] ] first_item = next(iter(items.values())) valid_date = date.fromisoformat(first_item["date"][:ISO_DATE_LENGTH]) return ParsedRates(valid_date=valid_date, rates=rates)