import re
import os
import time

from .logger import logger


def launchAttack(exploit, target_ip: str):
    start = time.time()
    flags_iterable = exploit(target_ip)
    if isinstance(flags_iterable, str):
        flags_iterable: list[str] = [flags_iterable]
    # for flag in flags_iterable:
    find_flags(flags_iterable)

    elapsed = time.time() - start

    logger.info(f"{exploit.__module__} took {elapsed:.2f} seconds")
    return


def find_flags(flags: list[str]):
    valid_flags = []

    if isinstance(flags, str):
        flags = [
            flags,
        ]
    print(os.environ["FLAG_REGEX"])
    if os.environ["FLAG_REGEX"] != "None":
        for flag in flags:
            m = re.finditer(pattern=os.environ["FLAG_REGEX"], string=flag)
            if m:
                for f in m:
                    valid_flags.append(f.group())

        if valid_flags:
            logger.info(f"Found valid flags: {valid_flags}")
        else:
            logger.info(f"Found no valid flags")
    else:
        logger.info(f"Returned:\n{flags}")
