"""Runtime directory for JSON maps, ``config/*.ini`` profiles, and SSH dotenv files."""

import os
from typing import Optional

_BASE: Optional[str] = None


def configure(app_dir: str) -> None:
    """
    Call once from ``fiwi.py`` with ``dirname(abspath(__file__))``.

    Loads ``remote_ssh.env`` / ``.fiwi_remote`` first, then ``config/<profile>.ini``
    (see :mod:`fiwi.config`), using :func:`os.environ.setdefault` so the shell wins.
    """
    global _BASE
    _BASE = os.path.abspath(app_dir)
    from fiwi.ssh import apply_fiwi_ssh_env

    apply_fiwi_ssh_env()
    from fiwi.config import apply_config_ini

    apply_config_ini(_BASE)


def base_dir() -> str:
    if _BASE is None:
        raise RuntimeError("fiwi.paths.configure() was not called (run via fiwi.py)")
    return _BASE


def config_dir() -> str:
    """Directory for INI profiles: ``<install>/config`` (add your own ``*.ini`` files)."""
    return os.path.join(base_dir(), "config")


def fiber_map_path() -> str:
    name = (os.environ.get("FIWI_FIBER_MAP") or "fiber_map.json").strip()
    if not name:
        name = "fiber_map.json"
    if os.path.isabs(name):
        return name
    return os.path.join(base_dir(), name)
