import functools
from typing import Callable, NoReturn, Any


def todo(what: str = "") -> NoReturn:
  """
  A placeholder for code that needs to be implemented.
  Raises a NotImplementedError with a descriptive message about the call site.
  Can be inserted anywhere in the code where functionality is yet to be implemented, without basedpyright screaming warnings.
  """
  import inspect
  import sys

  # Temporarily suppress the traceback to show a cleaner error message.
  sys.tracebacklimit = 0
  caller_frame = inspect.stack()[1]
  message = (
    f"\n\nTODO: {'Implementation needed' if not what else f'{f"Implement {what}" if not what.startswith("Implement") else what}'}\n"
    f"      in function '{caller_frame.function}'\n"
    f"      at {caller_frame.filename}:{caller_frame.lineno}\n"
  )
  raise NotImplementedError(message)


def todof(msg: str = "") -> Callable[..., Callable[..., NoReturn]]:
  """
  A decorator that can be used to mark entire functions as TODOs.
  When the decorated function is called, it raises a NotImplementedError with a descriptive message about the call site.
  """

  def wrapper(what: Callable[..., Any]) -> Callable[..., NoReturn]:  # pyright: ignore[reportExplicitAny]
    @functools.wraps(what)
    def inner(*args: Any, **kwargs: Any) -> NoReturn:  # pyright: ignore[reportExplicitAny, reportAny, reportUnusedParameter]
      import inspect
      import sys

      # Temporarily suppress the traceback to show a cleaner error message.
      sys.tracebacklimit = 0
      function_location = inspect.getfile(what)
      function_lines, start = inspect.getsourcelines(what)
      idx = 0
      while function_lines[idx].strip() == "":
        idx += 1
      while function_lines[idx].strip().startswith("@"):
        idx += 1
      function_lineno = start + idx
      message = (
        f"\n\nTODO: {'Implementation needed' if not msg else f'{"Implement " + msg if not msg.startswith("Implement") else msg}'}\n"
        f"      in function '{what.__name__}'\n"
        f"      at {function_location}:{function_lineno}\n"
      )
      raise NotImplementedError(message)

    return inner

  return wrapper


def todoc(msg: str = "") -> Callable[[type], type]:
  """
  A class decorator that can be used to mark entire classes as TODOs.
  When any method of the decorated class is called, it raises a NotImplementedError with a descriptive message about the call site.
  """

  def wrapper(cls: type) -> type:
    for attr_name in dir(cls):
      attr = getattr(cls, attr_name)  # pyright: ignore[reportAny]
      if isinstance(attr, (staticmethod, classmethod)):
        original_func = attr.__func__  # pyright: ignore[reportUnknownMemberType, reportUnknownVariableType]
        if hasattr(original_func, "__wrapped__"):  # pyright: ignore[reportUnknownArgumentType]
          continue
        decorated_func = todof(msg)(original_func)
        if isinstance(attr, staticmethod):
          setattr(cls, attr_name, staticmethod(decorated_func))
        else:
          setattr(cls, attr_name, classmethod(decorated_func))
      elif callable(attr):  # pyright: ignore[reportAny]
        if hasattr(attr, "__wrapped__"):
          continue
        # avoid wrapping __class__, __dict__, __module__, __weakref__, etc.
        if attr_name.startswith("__") and attr_name.endswith("__"):
          continue
        decorated_method = todof(msg)(attr)
        setattr(cls, attr_name, decorated_method)

    return cls

  return wrapper
