"""
Chemins et infos runtime multi-plateforme (Windows, macOS, Linux).

Prepare l'installation future sur Mac sans dupliquer la logique metier.
"""

from __future__ import annotations

import os
import sys
from pathlib import Path

APP_NAME = "Paychek Safeguard"
APP_DIR_NAME = "PaychekCompanion"


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


def bundle_dir() -> Path | None:
    """Dossier PyInstaller (_MEIPASS) si build frozen legacy."""
    if not is_frozen():
        return None
    meipass = getattr(sys, "_MEIPASS", None)
    return Path(meipass) if meipass else None


def app_src_dir() -> Path:
    """Racine du code Python (src/) — dev, kit portable, ou bundle frozen."""
    bundled = bundle_dir()
    if bundled is not None:
        return bundled / "src"
    return Path(__file__).resolve().parents[1]


def static_dir() -> Path:
    return app_src_dir() / "static"


def project_root() -> Path:
    """Racine projet (dev) ou racine du kit Windows (parent de src/)."""
    if is_frozen():
        return Path(sys.executable).resolve().parent
    return Path(__file__).resolve().parents[2]


def user_data_dir() -> Path:
    """
    Dossier utilisateur pour config, logs et donnees persistantes.

    - macOS  : ~/Library/Application Support/PaychekCompanion
    - Windows: %LOCALAPPDATA%\\PaychekCompanion
    - Linux  : ~/.local/share/PaychekCompanion
    """
    home = Path.home()
    if sys.platform == "darwin":
        base = home / "Library" / "Application Support" / APP_DIR_NAME
    elif sys.platform == "win32":
        local = os.environ.get("LOCALAPPDATA")
        base = Path(local) / APP_DIR_NAME if local else home / APP_DIR_NAME
    else:
        base = home / ".local" / "share" / APP_DIR_NAME

    base.mkdir(parents=True, exist_ok=True)
    return base


def logs_dir() -> Path:
    path = user_data_dir() / "logs"
    path.mkdir(parents=True, exist_ok=True)
    return path


def env_file_candidates() -> list[Path]:
    """Ordre de recherche du fichier .env (dev projet puis install utilisateur)."""
    paths = [user_data_dir() / ".env"]
    if not is_frozen():
        paths.append(project_root() / ".env")
    else:
        paths.append(project_root() / ".env")
    return paths


def ensure_user_env(seed_from: Path | None = None) -> Path:
    """Cree %LOCALAPPDATA%\\PaychekCompanion\\.env au premier lancement."""
    target = user_data_dir() / ".env"
    if target.is_file():
        return target
    if seed_from and seed_from.is_file():
        target.write_text(seed_from.read_text(encoding="utf-8"), encoding="utf-8")
        return target
    # Minimal defaults — must match addon PaychekSafeguard.json webhook_secret.
    target.write_text(
        "WEBHOOK_SECRET=change-me-before-production\n"
        "HOST=127.0.0.1\n"
        "PORT=8080\n"
        "EXECUTION_MODE=hybrid\n"
        "TRADING_ENABLED=true\n",
        encoding="utf-8",
    )
    return target


def resolve_env_file() -> Path:
    for path in env_file_candidates():
        if path.is_file():
            return path
    # Create defaults so webhook_secret matches the NinjaTrader addon JSON.
    return ensure_user_env()


def runtime_info() -> dict[str, str]:
    return {
        "app": APP_NAME,
        "platform": sys.platform,
        "python": sys.version.split()[0],
        "project_root": str(project_root()),
        "user_data_dir": str(user_data_dir()),
        "env_file": str(resolve_env_file()),
    }
