from __future__ import annotations

import os
import sys
from pathlib import Path


PRODUCT_NAME = "ProcessMonitor"


def is_frozen() -> bool:
    return bool(getattr(sys, "frozen", False))


def application_root() -> Path:
    """Directory containing the distributable EXEs, or the source repository root."""
    override = os.environ.get("PROCESSMONITOR_APP_ROOT")
    if override:
        return Path(override).expanduser().resolve()
    if is_frozen():
        return Path(sys.executable).resolve().parent
    return Path(__file__).resolve().parent.parent


def runtime_root() -> Path:
    """Stable writable state root; never PyInstaller's temporary extraction directory."""
    override = os.environ.get("PROCESSMONITOR_DATA_ROOT")
    if override:
        return Path(override).expanduser().resolve()
    if not is_frozen():
        return application_root() / "data"
    local_data = os.environ.get("LOCALAPPDATA")
    base = Path(local_data) if local_data else Path.home() / "AppData" / "Local"
    return base / PRODUCT_NAME


def config_path() -> Path:
    override = os.environ.get("PROCESSMONITOR_CONFIG")
    return Path(override).expanduser().resolve() if override else application_root() / "config" / "process_monitor_config.json"


def database_path() -> Path:
    return runtime_root() / "processmonitor.db"


def relay_runtime_dir() -> Path:
    return runtime_root() / "relay_runtime"


def relay_executable() -> Path:
    return application_root() / "ProcessMonitorRelay.exe"
