import hashlib
import importlib
from typing import TYPE_CHECKING, Any

import yaml
from agentic_chat_ui.src.constants import CONFIG_PATH

if TYPE_CHECKING:
    from agentic_chat_ui.src.view_runners import ViewRunner


def load_class(path: str) -> Any:
    module_path, class_name = path.rsplit(".", 1)
    module = importlib.import_module(module_path)
    return getattr(module, class_name)


def get_view(config_path: str = CONFIG_PATH) -> "ViewRunner[Any]":
    with open(config_path) as f:
        yaml_config = yaml.safe_load(f)
        klass = load_class(yaml_config["module_path"])
        if not isinstance(klass, type):
            raise TypeError(f"Loaded object {klass!r} is not a class")
        if not issubclass(klass, ViewRunner):
            raise TypeError(f"Loaded class {klass.__name__} is not a subclass of ViewRunner")
        instance = klass.from_settings()
        return instance


def hash_password(password: str) -> str:
    return hashlib.sha256(password.encode("utf-8")).hexdigest()
