#!python
# -*- coding: utf-8 -*-
"""
Twinshare CLI entry point script.
This script is installed as a command-line tool when the package is installed.
"""

import os
import sys
import subprocess
import importlib.util

# Add the parent directory to the Python path to ensure the package is found
package_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, package_dir)

# Function to check if a module is installed
def is_module_installed(module_name):
    return importlib.util.find_spec(module_name) is not None

# Check for required dependencies
required_modules = ['yaml', 'aiohttp', 'asyncio', 'tabulate', 'cryptography', 'daemon', 'netifaces']
missing_modules = []

for module in required_modules:
    if not is_module_installed(module):
        missing_modules.append(module)

if missing_modules:
    print(f"Missing required dependencies: {', '.join(missing_modules)}")
    
    # Try to install the missing dependencies directly
    try:
        for module in missing_modules:
            module_name = module
            if module == 'yaml':
                module_name = 'pyyaml'
            elif module == 'daemon':
                module_name = 'python-daemon'
                
            print(f"Installing {module_name}...")
            # Use --user flag to install in user's home directory
            subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--user', module_name])
        
        print("Dependencies installed successfully. Please run the command again.")
        sys.exit(0)
    except Exception as e:
        print(f"Error installing dependencies: {e}")
        print("\nPlease install the missing dependencies manually:")
        for module in missing_modules:
            module_name = module
            if module == 'yaml':
                module_name = 'pyyaml'
            elif module == 'daemon':
                module_name = 'python-daemon'
            print(f"pip install --user {module_name}")
        
        print("\nOr run the install_package.sh script to set up everything automatically.")
        sys.exit(1)

# Now try to import and run the main function directly
# This avoids the circular import issue in src/__init__.py
try:
    # Import the main module directly without going through the package __init__
    sys.path.insert(0, os.path.join(package_dir, 'src'))
    from src.cli.main import main
    sys.exit(main())
except ImportError as e:
    print(f"Error importing twinshare modules: {e}")
    print("This could be due to an installation issue or circular imports.")
    print("\nTrying alternative import method...")
    
    try:
        # Try running the module directly as a script
        cli_main_path = os.path.join(package_dir, 'src', 'cli', 'main.py')
        if os.path.exists(cli_main_path):
            # Use execfile-like functionality for Python 3
            main_globals = {'__file__': cli_main_path, '__name__': '__main__'}
            with open(cli_main_path) as f:
                exec(compile(f.read(), cli_main_path, 'exec'), main_globals)
            sys.exit(0)
        else:
            print(f"Could not find the CLI main module at {cli_main_path}")
    except Exception as e2:
        print(f"Alternative method also failed: {e2}")
    
    print("\nPlease try installing the package in a virtual environment:")
    print("\npython3 -m venv venv")
    print("source venv/bin/activate")
    print(f"cd {package_dir} && pip install -e .")
    print("\nOr run the install_package.sh script to set up everything automatically.")
    sys.exit(1)
