import logging
import subprocess
import threading
from datetime import datetime
from typing import Union, List

logger = logging.getLogger(__name__)


def core_call_hook(hook_name: str, args: Union[str, List[str]]):
    if args:
        t = threading.Thread(
            target=_hook_call_handler,
            name=f"core-{hook_name}-hook",
            args=(datetime.now(), hook_name, args),
            daemon=True,
        )
        t.start()


def _hook_call_handler(dt: datetime, hook_name: str, args: Union[str, List[str]]):
    try:
        subprocess.check_call(args, start_new_session=True)
    except subprocess.CalledProcessError as e:
        logger.error("Calling %s hook at %s failed %s", hook_name, dt, e.returncode)
    except Exception:
        logger.exception("Calling %s hook at %s failed unexpectedly", hook_name, dt)
    else:
        logger.info("Calling %s hook at %s succeeded", hook_name, dt)
