"""
setup.py — Provides proper metadata and post-install PATH auto-fix.
"""

import atexit
import os
import platform
from pathlib import Path
from setuptools import setup
from setuptools.command.install import install
from setuptools.command.develop import develop


def _auto_fix_path():
    """Add ~/.local/bin to PATH in shell configs. Linux/macOS only."""
    try:
        if platform.system() == "Windows":
            return

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

        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")
                    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 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

        try:
            local_bin.mkdir(parents=True, exist_ok=True)
        except (PermissionError, OSError):
            pass

    except Exception:
        pass


class PostInstall(install):
    def run(self):
        install.run(self)
        _auto_fix_path()


class PostDevelop(develop):
    def run(self):
        develop.run(self)
        _auto_fix_path()


atexit.register(_auto_fix_path)

setup(
    name="jyoti",
    version="1.0.3",
    cmdclass={
        "install": PostInstall,
        "develop": PostDevelop,
    },
)
