# from pathlib import Path


# def run_file(file_path: str):
#     """
#     Reads a .prasad file and prints the source code.
#     Later this will execute the language.
#     """

#     path = Path(file_path)

#     if not path.exists():
#         print(f"Error: File '{file_path}' not found.")
#         return

#     if path.suffix != ".prasad":
#         print("Error: Only .prasad files are supported.")
#         return

#     try:
#         with open(path, "r", encoding="utf-8") as file:
#             source_code = file.read()

#         print("----- PRASAD SOURCE CODE -----")
#         print(source_code)
#         print("----- END OF FILE -----")

#     except Exception as e:
#         print(f"Error reading file: {e}")


import os

from .interpreter import Interpreter
from .lexer import Lexer
from .parser import Parser
from .package_config import PackageConfigError, load_package_config


def run_file(file_path):
    # Allow running a package directory or a prasad.toml file.
    config_path = None
    if os.path.isdir(file_path):
        config_path = os.path.join(file_path, "prasad.toml")
    elif os.path.basename(file_path).lower() == "prasad.toml":
        config_path = file_path

    if config_path is not None:
        abs_config = os.path.abspath(config_path)
        if not os.path.exists(abs_config):
            raise FileNotFoundError(f"No such file: '{config_path}'")

        config_dir = os.path.dirname(abs_config)
        try:
            toml_text = open(abs_config, "r", encoding="utf-8").read()
            pkg = load_package_config(toml_text)
        except PackageConfigError as e:
            raise ValueError(f"Invalid prasad.toml: {e}")

        main_path = pkg.entry
        if not os.path.isabs(main_path):
            main_path = os.path.join(config_dir, main_path)
        abs_main_path = os.path.abspath(main_path)

        with open(abs_main_path, "r", encoding="utf-8") as f:
            source = f.read()

        lexer = Lexer(source)
        tokens = lexer.tokenize()
        program = Parser(tokens, source=source).parse()

        interpreter = Interpreter(base_dir=config_dir)
        for dep in pkg.dependency_names:
            interpreter._import_module(dep, None)

        interpreter.run(program)
        return

    abs_main_path = os.path.abspath(file_path)
    try:
        with open(abs_main_path, "r", encoding="utf-8") as f:
            source = f.read()
    except FileNotFoundError:
        # Try in parent directory (useful when running from subdirs like vscode-prasad-syntax)
        parent_path = os.path.join(os.path.dirname(os.getcwd()), file_path)
        try:
            abs_main_path = os.path.abspath(parent_path)
            with open(abs_main_path, "r", encoding="utf-8") as f:
                source = f.read()
        except FileNotFoundError:
            raise FileNotFoundError(
                f"No such file or directory: '{file_path}' (tried current and parent directory)"
            )

    lexer = Lexer(source)
    tokens = lexer.tokenize()

    if os.environ.get("PRASAD_DEBUG_TOKENS") == "1":
        print("TOKENS:")
        for token in tokens:
            print(token)

    program = Parser(tokens, source=source).parse()
    Interpreter(base_dir=os.path.dirname(abs_main_path)).run(program)
