from pathlib import Path
from .lexer import LexerInfo, lexical_analysis, Token
from .interpreter import InterpreterState


def exec_file(interpreter_state: InterpreterState, filename: str) -> bool:
    path = Path(filename)

    if not path.exists():
        print(f"Cannot read file: {filename}")
        return False

    try:
        code = path.read_text()
    except Exception:
        print(f"Cannot read file: {filename}")
        return False

    lexer_info = LexerInfo(filename=filename, source_code=code)

    tokens: list[Token] = lexical_analysis(lexer_info)

    for tok in tokens:
        if not interpreter_state.execute(tok):
            print("A runtime error occurred!")
            return False

    return True

def run_file(filename: str) -> int:
    print(f"Executing file: {filename}")

    interpreter_state = InterpreterState()

    success = exec_file(interpreter_state, filename)

    return 0 if success else 1
