"""Default data directory resolution.

Each LedGrab install/checkout uses its own data directory by default —
a cwd-relative ``data`` folder — so running two versions side-by-side does
not mix their databases together.

Precedence:
  1. ``LEDGRAB_STORAGE__DATABASE_FILE`` / ``LEDGRAB_ASSETS__ASSETS_DIR`` env
     vars (used by the Android entry point and fine-grained overrides).
  2. ``storage.database_file`` / ``assets.assets_dir`` in config.yaml.
  3. ``LEDGRAB_DATA_DIR`` env var (one-line override for the whole data
     dir — useful for dev launchers that want to isolate from prod).
  4. ``./data`` relative to the process working directory.
"""

import os
from pathlib import Path

_ENV_DATA_DIR = "LEDGRAB_DATA_DIR"


def default_data_dir() -> Path:
    """Return the directory where data files live by default.

    Honours the ``LEDGRAB_DATA_DIR`` env var; otherwise returns ``./data``.
    Callers should treat the result as the *parent* of ``ledgrab.db`` and
    ``assets/``.
    """
    override = os.environ.get(_ENV_DATA_DIR)
    if override:
        return Path(override)
    return Path("data")


def legacy_db_candidates() -> list[Path]:
    """Return cwd-relative database paths that predate :func:`default_data_dir`.

    Used by the startup migration in ``main.py`` to rescue data that was
    previously written by older versions (or by dev runs from inside ``server/``).
    Order matters: first existing match wins.
    """
    cwd = Path.cwd()
    return [
        cwd / "data" / "ledgrab.db",
        cwd / "server" / "data" / "ledgrab.db",
    ]


def legacy_assets_candidates() -> list[Path]:
    """Return cwd-relative assets directories paired with :func:`legacy_db_candidates`."""
    cwd = Path.cwd()
    return [
        cwd / "data" / "assets",
        cwd / "server" / "data" / "assets",
    ]
