import aiohttp
import re


async def find_repos_for_rpms(rpms, build, arch="x86_64"):
    """ Find content sets for rpms by looking at Brew logs
    """
    log_url = f"http://download.eng.bos.redhat.com/brewroot/packages/{build['name']}/{build['version']}/{build['release']}/data/logs/{arch}.log"
    async with aiohttp.ClientSession() as session:
        async with await session.get(log_url) as response:
            log = await response.text()
    # looking for lines in logs like
    # `2020-07-18 10:52:00,888 - atomic_reactor.plugins.imagebuilder - INFO -  java-11-openjdk      i686   1:11.0.8.10-0.el7_8 rhel-server-rpms-x86_64  215 k`
    pattern = re.compile(r"atomic_reactor.plugins.imagebuilder - INFO -\s+([\w-]+)\s+\w+\s+([\w.-]+)\s+([\w-]+)\s+[\d.]+")
    rpm_to_content_set = {}

    for line in log.split("\n"):
        match = pattern.search(line)
        if not match:
            continue
        name = match[1]
        version_release = match[2]
        content_set = match[3]
        if f"{name}-{version_release}" in rpms:
            rpm_to_content_set[f"{name}-{version_release}"] = content_set

    return rpm_to_content_set