from pathlib import Path
import tempfile

from minecraft_datapack_language.mdl_parser import MDLParser
from minecraft_datapack_language.mdl_compiler import MDLCompiler


def test_user_snippet_while_and_temp_vars_inline():
    src = (
        'pack "test1" "Generated by MDL CLI" 82;\n'
        'namespace "test1";\n\n'
        '// Variables\n'
        'var num counter<@s> = 0;\n'
        'var num global_timer<@a> = 0;\n\n'
        'function test1:testfunc {\n'
        '    var num testfunccount1<@s> = 10;\n'
        '    while $testfunccount1<@s>$ > 0 {\n'
        '        say "Hello from testfunc!";\n'
        '        testfunccount1<@s> = $testfunccount1<@s>$ - 1;\n'
        '    }\n'
        '}\n'
    )

    parser = MDLParser()
    ast = parser.parse(src)
    with tempfile.TemporaryDirectory() as tmp:
        out = Path(tmp)
        MDLCompiler().compile(ast, str(out))
        func_dir = out / 'data' / 'test1' / 'function'
        # parent file exists and calls generated while function
        parent = (func_dir / 'testfunc.mcfunction').read_text()
        assert 'function test1:testfunc__while_' in parent
        # loop body file contains inlined temp ops and recursion
        while_files = sorted(func_dir.glob('testfunc__while_*.mcfunction'))
        assert while_files, 'expected generated while function file'
        body = while_files[0].read_text()
        assert 'tellraw @a {"text":"Hello from testfunc!"}' in body
        assert 'scoreboard players operation @s temp_' in body
        assert 'scoreboard players remove @s temp_' in body
        assert 'scoreboard players operation @s testfunccount1 = @s temp_' in body
        assert 'execute if score @s testfunccount1 matches 1.. run function test1:testfunc__while_' in body


