"""Allow running the core as ``python -m armorer.core``."""

import atexit
import logging
import os
import signal
from pathlib import Path

from armorer.config import resolve_armorer_config_dir
from armorer.core.entry import start_core
from armorer.core.singleton import _claim_host_core_singleton, _release_owned_pid_file

logger = logging.getLogger("ArmorerCore")


def main():
    installed_dir = os.getenv("INSTALLED_DIR")
    if not installed_dir:
        repo_installed = Path(__file__).resolve().parents[3] / "installed"
        if os.path.exists("/.dockerenv"):
            installed_dir = "/app/installed"
        elif repo_installed.exists():
            installed_dir = str(repo_installed)
        else:
            installed_dir = str(Path.cwd() / "installed")
    config_path = resolve_armorer_config_dir()
    config_path.mkdir(parents=True, exist_ok=True)
    pid_file = config_path / "core-host.pid"

    if not _claim_host_core_singleton(config_path):
        logger.info("Armorer host core is already active; exiting duplicate process.")
        raise SystemExit(0)

    atexit.register(_release_owned_pid_file, pid_file, os.getpid())

    def _handle_exit_signal(_signum, _frame):
        _release_owned_pid_file(pid_file, os.getpid())
        raise SystemExit(0)

    for sig in (signal.SIGTERM, signal.SIGINT):
        try:
            signal.signal(sig, _handle_exit_signal)
        except Exception:
            pass

    start_core(installed_dir, str(config_path))


if __name__ == "__main__":
    main()
