# algo_analyze/__main__.py
import importlib.util
import sys
from .inspector import inspect


def load_function(file_path, func_name=None):
    """Dynamically load a function from a Python file."""
    spec = importlib.util.spec_from_file_location("user_module", file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)

    if func_name:
        if func_name not in module.__dict__:
            print(f"Function '{func_name}' not found in {file_path}")
            sys.exit(1)
        return module.__dict__[func_name]
    return None


def main():
    if len(sys.argv) < 3:
        print("Usage: python -m algo_analyze <file.py> <function> [args...]")
        sys.exit(1)

    file_path = sys.argv[1]
    func_name = sys.argv[2]
    func_args = sys.argv[3:]

    # Convert numeric arguments if possible
    args = []
    for arg in func_args:
        if arg.isdigit():
            args.append(int(arg))
        else:
            try:
                args.append(float(arg))
            except ValueError:
                args.append(arg)

    fn = load_function(file_path, func_name)
    if fn:
        # Decorate function for inspection
        wrapped_fn = inspect(fn)
        report = wrapped_fn(*args)  # Call decorated function with arguments
        print(report)  # Print only once
    else:
        print(f"No function specified in {file_path}. Nothing to inspect.")


if __name__ == "__main__":
    main()
