import re
from typing import Generator


def convert_markdown_file(md_filename: str, out_filename: str):
    with open(md_filename, "r") as f_in:
        with open(out_filename, "w") as f_out:
            f_out.write('def run_test():\n')
            for block in markdown_to_code([line for line in f_in]):
                f_out.write(block + '\n')


def markdown_to_code(lines: list[str], language: str = "python") -> Generator[str, None, None]:
    regex = re.compile(
        r"(?P<start>^```\s*(?P<block_language>(\w|-)*)\n)(?P<code>.*?\n)(?P<end>```)",
        re.DOTALL | re.MULTILINE,
    )
    blocks = [
        (match.group("block_language"), match.group("code"))
        for match in regex.finditer("".join(lines))
    ]

    ret_block_flag = False

    for block_language, block in blocks:
        if block_language == language:
            lines = [line for line in block.splitlines() if line.strip()]
            ret_block_flag = lines[-1] if '=' not in lines[-1] else None

            yield ''
            yield '    print("---------------------------------------------------------")'
            yield ''
            if ret_block_flag:
                yield from ['    ' + str(line) for line in block.splitlines()[:-1]]
            else:
                yield from ['    ' + str(line) for line in block.splitlines()]
            yield f'    print("-- Result (({ret_block_flag})):")'
            yield f'    print(({ret_block_flag}).__repr__().strip())'

        elif ret_block_flag:
            yield '    ref_str = """'
            yield from [str(line) for line in block.splitlines()]
            yield '"""'
            yield f'    print("-- Reference (({ret_block_flag})):")'
            yield '    print(ref_str.strip())'
            yield f'    assert ({ret_block_flag}).__repr__().strip() == ref_str.strip()'


def test_readme():
    convert_markdown_file('README.md', 'tests/autogenerated_readme.py')
    import autogenerated_readme
    autogenerated_readme.run_test()
