"""
setup.py — Custom setup with post-install PATH auto-configuration.

On Linux/macOS, pip installs CLI scripts to ~/.local/bin/ which might NOT
be in PATH. This setup.py auto-adds it to shell config files (.bashrc,
.zshrc, .profile, etc.) during install so the `jyoti` command works
immediately in a new terminal.
"""

import atexit
import os
import sys
import platform
from pathlib import Path
from setuptools import setup


def _auto_fix_path():
    """
    Automatically add ~/.local/bin to PATH in user's shell config files.
    This runs as an atexit hook when pip finishes building from source.
    Safe: only adds if not already present. Only runs on Linux/macOS.
    """
    try:
        # Not needed on Windows — pip adds Scripts/ to PATH automatically
        if platform.system() == "Windows":
            return

        home = Path.home()
        local_bin = home / ".local" / "bin"

        # Shell config files to check/modify
        shell_configs = [
            home / ".bashrc",
            home / ".zshrc",
            home / ".profile",
            home / ".bash_profile",
        ]

        path_export_line = (
            '\n# Added by jyoti package (Happy Birthday! 🎂)\n'
            'export PATH="$HOME/.local/bin:$PATH"\n'
        )

        fixed = False
        for config_file in shell_configs:
            if config_file.exists():
                try:
                    content = config_file.read_text(encoding="utf-8", errors="ignore")
                    # Only add if .local/bin is not already referenced
                    if ".local/bin" not in content:
                        with open(config_file, "a", encoding="utf-8") as f:
                            f.write(path_export_line)
                        fixed = True
                except (PermissionError, OSError):
                    continue

        # If no shell config existed at all, create .bashrc with the PATH
        if not fixed:
            bashrc = home / ".bashrc"
            if not bashrc.exists():
                try:
                    with open(bashrc, "w", encoding="utf-8") as f:
                        f.write(path_export_line)
                except (PermissionError, OSError):
                    pass

        # Also try creating the .local/bin directory if it doesn't exist
        try:
            local_bin.mkdir(parents=True, exist_ok=True)
        except (PermissionError, OSError):
            pass

    except Exception:
        # Never let PATH fixing crash the installation
        pass


# Register the PATH fix to run when this process exits
# (pip runs setup.py during install from source, atexit fires on clean exit)
atexit.register(_auto_fix_path)

setup()
