import os
import excel2xx.codegen as codegen
import logging
import tempfile

root_dir = os.path.dirname(os.path.dirname(__file__))
test_dir = os.path.dirname(__file__)

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)


def test_codegen_md():
    with tempfile.TemporaryDirectory(prefix="codegen-") as d:
        log.info("temp directory: %s", d)
        for fname in ["abc", "def", "ghi"]:
            write_file(d + f"/{fname}.md.mako", example_md[0])
            pass

        ctx = {
            "from": "testcase",
        }
        src = d + "/*.mako"
        codegen.generate(src, ctx, note="")
        for fname in ["abc", "def", "ghi"]:
            expected = example_md[1].replace("${__file__}", d + f"/{fname}.md.mako")
            assert expected == read_file(d + f"/{fname}.md")
        pass
    pass


def read_file(fpath) -> str:
    log.info("read_file %s", fpath)
    with open(fpath) as fp:
        return fp.read()
    pass


def write_file(fpath, content: str):
    log.info("write_file %s", fpath)
    with open(fpath, "w") as fp:
        return fp.write(content)
    pass


example_md = [
    """
This is generated by template file "${__file__}"

```
% for i in range(3):
${i} ** 2 = ${i**2}
% endfor
```
""",
    """
This is generated by template file "${__file__}"

```
0 ** 2 = 0
1 ** 2 = 1
2 ** 2 = 4
```
""",
]
