"""Composition root — holds config, stash, and service layer."""

import os
import subprocess  # nosec B404

from mb_stash.config import Config
from mb_stash.core.service import Service
from mb_stash.core.stash import Stash
from mb_stash.daemon.server import run_server


class Core:
    """Application composition root.

    Creates and owns all shared resources (stash, services).
    Passed to CLI commands via ``CoreContext``.
    """

    def __init__(self, config: Config) -> None:  # noqa: D107
        self.config = config
        self.stash = Stash(config.stash_path)
        self.service = Service(self.stash, config)

    def close(self) -> None:
        """Release resources — wipe key material from memory."""
        self.stash.lock()

    def run_daemon(self) -> None:
        """Start or run the daemon process.

        If not adopted by init/launchd, re-spawns as a proper daemon.
        Otherwise runs the server directly.
        """
        if os.getppid() != 1:
            subprocess.Popen(  # noqa: S603  # nosec B603
                [*self.config.cli_base_args(), "daemon"],
                stdin=subprocess.DEVNULL,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.DEVNULL,
                start_new_session=True,
            )
            return
        run_server(self.config, self.stash)
