"""Banka CREDITAS: HTML table of non-cash rates, which the bank itself calls indicative."""
import re
from datetime import date
from app.models import ParsedRates
from app.sources.base import make_rate, parse_comma_decimal
VALIDITY_PATTERN = re.compile(r"Kurzy platné k (\d{1,2})\. ?(\d{1,2})\. ?(\d{4})")
ROW_MARKER = '
[A-Z]{3})">(?P=currency).*?'
r'Jednotka\s*.*?'
r'Nakupujeme v CZK\s*\s*'
r"(?:]*>)?(?P[\d,]+) CZK.*?"
r'Prodáváme v CZK
\s*\s*'
r"(?:]*>)?(?P[\d,]+) CZK",
re.DOTALL,
)
def parse(document: str) -> ParsedRates:
validity = VALIDITY_PATTERN.search(document)
if validity is None:
raise ValueError("Creditas validity date not found")
day, month, year = validity.groups()
# Matching row by row keeps prices of one currency from leaking into another one.
rows = (ROW_PATTERN.search(chunk) for chunk in document.split(ROW_MARKER)[1:])
rates = [
make_rate(
currency=row["currency"],
amount=int(row["amount"]),
buy=parse_comma_decimal(row["buy"]),
sell=parse_comma_decimal(row["sell"]),
)
for row in rows
if row is not None
]
return ParsedRates(valid_date=date(int(year), int(month), int(day)), rates=rates)