"""
frozen_path — centralized path resolution for PyInstaller frozen + dev modes.

Import this module in any file that currently does:
    ROOT = pathlib.Path(__file__).parent.parent.absolute()
    LOG_DIR = ROOT / "logs"

In frozen mode, ROOT resolves to %APPDATA%/GoldAutoTrade (writable, persistent).
In dev mode, ROOT resolves to the project source tree.

This prevents the classic PyInstaller path drift where writers write to
the read-only _MEIPASS temp dir and readers read from AppData.
"""

from __future__ import annotations

import os
import sys
from pathlib import Path


def _resolve_app_root() -> Path:
    """Return the writable, persistent application root directory."""
    if getattr(sys, 'frozen', False):
        # PyInstaller: use %APPDATA%/GoldAutoTrade
        if sys.platform == 'win32':
            return Path(os.environ.get('APPDATA', os.path.expanduser('~'))) / 'GoldAutoTrade'
        else:
            return Path(os.environ.get('HOME', os.path.expanduser('~'))) / 'GoldAutoTrade'
    else:
        # Dev mode: use project source tree root
        # frozen_path.py lives at project root
        return Path(__file__).resolve().parent


# Singleton — resolved once at import time
APP_ROOT: Path = _resolve_app_root()

# Convenience shortcuts
LOGS_DIR: Path = APP_ROOT / 'logs'
DATA_DIR: Path = APP_ROOT / 'data'
CONFIG_DIR: Path = APP_ROOT / 'config'
LOG_DIR: Path = LOGS_DIR

# Ensure directories exist (dev mode: project already has them)
LOGS_DIR.mkdir(parents=True, exist_ok=True)
DATA_DIR.mkdir(parents=True, exist_ok=True)
CONFIG_DIR.mkdir(parents=True, exist_ok=True)


def app_root() -> Path:
    """Return the writable application root directory."""
    return APP_ROOT


def logs_dir() -> Path:
    """Return the writable logs directory."""
    return LOGS_DIR


def data_dir() -> Path:
    """Return the writable data directory."""
    return DATA_DIR


def config_dir() -> Path:
    """Return the writable config directory."""
    return CONFIG_DIR
