#!/usr/bin/env python3
"""
Install SealVera autoload process-wide via a .pth file in site-packages.

This makes SEALVERA_AUTOLOAD=1 activate SealVera in EVERY Python process,
including subprocesses, without any code changes.

Usage:
    python -m sealvera.install_autoload          # install
    python -m sealvera.install_autoload --remove # remove
    python -m sealvera.install_autoload --check  # check status
"""

import sys
import site
import os

PTH_NAME = "sealvera-autoload.pth"
PTH_CONTENT = "import sealvera.autoload\n"


def get_site_packages():
    candidates = []
    try:
        candidates.extend(site.getsitepackages())
    except AttributeError:
        pass
    try:
        candidates.append(site.getusersitepackages())
    except AttributeError:
        pass
    # Filter to writable ones
    return [p for p in candidates if os.path.isdir(p) and os.access(p, os.W_OK)]


def install():
    dirs = get_site_packages()
    if not dirs:
        print("ERROR: No writable site-packages found. Try running with sudo or in a virtualenv.")
        sys.exit(1)

    target = dirs[0]
    pth    = os.path.join(target, PTH_NAME)

    with open(pth, "w") as f:
        f.write(PTH_CONTENT)

    print(f"✓ Installed: {pth}")
    print(f"\nSealVera autoload is now active for all Python processes.")
    print(f"Set SEALVERA_API_KEY and SEALVERA_AUTOLOAD=1 in your environment to activate.\n")
    print(f"To remove: python -m sealvera.install_autoload --remove")


def remove():
    removed = []
    for d in get_site_packages():
        pth = os.path.join(d, PTH_NAME)
        if os.path.exists(pth):
            os.remove(pth)
            removed.append(pth)
    if removed:
        for p in removed:
            print(f"✓ Removed: {p}")
    else:
        print("Nothing to remove.")


def check():
    found = []
    for d in get_site_packages():
        pth = os.path.join(d, PTH_NAME)
        if os.path.exists(pth):
            found.append(pth)
    if found:
        print("✓ SealVera autoload .pth installed:")
        for p in found:
            print(f"  {p}")
    else:
        print("✗ SealVera autoload not installed process-wide.")
        print("  Run: python -m sealvera.install_autoload")


if __name__ == "__main__":
    if "--remove" in sys.argv:
        remove()
    elif "--check" in sys.argv:
        check()
    else:
        install()
