from pathlib import Path

from microbasic_compiler.lexer import tokenize
from microbasic_compiler.tokens import TokenType


def test_numbers():
    toks = tokenize("120 0xA1 0b101")
    values = [t.value for t in toks if t.type == TokenType.INTEGER]
    assert values == ["120", "0xA1", "0b101"]


def test_comment_ignored():
    toks = [
        t
        for t in tokenize("x = 1 ' trailing comment\n")
        if t.type not in (TokenType.NEWLINE, TokenType.EOF)
    ]
    assert [t.value for t in toks] == ["x", "=", "1"]


def test_string_escapes():
    toks = tokenize('"Hello\\n"')
    assert toks[0].type == TokenType.STRING
    assert toks[0].value == "Hello\n"


def test_keyword_case_insensitive():
    toks = tokenize("If a Then\nEnd If\n")
    kw_values = [t.value for t in toks if t.type == TokenType.KEYWORD]
    assert kw_values == ["if", "then", "end", "if"]


def test_label():
    toks = tokenize("top:\ngoto top\n")
    assert toks[0].type == TokenType.LABEL
    assert toks[0].value == "top"


def test_compound_assignment_operator():
    toks = tokenize("x += 1")
    op_values = [t.value for t in toks if t.type == TokenType.OP]
    assert op_values == ["+="]


def test_example_script_tokenizes_without_error():
    source = Path(__file__).parent.parent / "examples" / "blink.mb"
    tokens = tokenize(source.read_text())
    assert tokens[-1].type == TokenType.EOF
