"""
CARL Control Panel - Main entry point for pip install.
"""
import os
import sys
import threading
import webbrowser
import time


def main():
    """Main entry point."""
    # Change to package directory so Flask finds templates/static
    package_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(package_dir)

    # Import here to ensure correct working directory
    from carl_control_panel.app import app, init_database, load_active_profile

    # Initialize
    init_database()
    load_active_profile()

    # Open browser after short delay
    def open_browser():
        time.sleep(1.5)
        webbrowser.open('http://127.0.0.1:5050')

    threading.Thread(target=open_browser, daemon=True).start()

    # Run Flask
    print("CARL Control Panel starting...")
    print("Opening http://127.0.0.1:5050 in your browser...")
    app.run(host='127.0.0.1', port=5050, debug=False, use_reloader=False)


if __name__ == "__main__":
    main()
