import subprocess
import sys
import os
import signal

# Handle graceful shutdown
def signal_handler(sig, frame):
    print("\n[INFO] Shutting down gracefully...")
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

if __name__ == "__main__":
    # Use pyenv python if available, otherwise fall back to venv or system python
    python_exec = sys.executable

    # Check for pyenv virtualenv
    pyenv_root = os.environ.get('PYENV_ROOT')
    if pyenv_root:
        pyenv_python = os.path.join(pyenv_root, 'versions', 'autokanban', 'bin', 'python')
        if os.path.exists(pyenv_python):
            python_exec = pyenv_python

    # Fall back to local venv
    if python_exec == sys.executable:
        venv_python = os.path.join(os.path.dirname(__file__), '.venv', 'bin', 'python')
        if os.path.exists(venv_python):
            python_exec = venv_python

    print(f"[INFO] Using Python: {python_exec}")
    print(f"[INFO] Starting AutoKanban on http://0.0.0.0:8000")

    # Launch the FastAPI app with uvicorn (no --reload for production)
    try:
        subprocess.run([
            python_exec, '-m', 'uvicorn', 'app.main:app',
            '--host', '0.0.0.0', '--port', '8000'
        ])
    except KeyboardInterrupt:
        print("\n[INFO] Shutting down gracefully...")
        sys.exit(0)
