#!/usr/bin/env python3
"""
Sharey B2 Setup Script
"""
import os
import sys
import subprocess
import shutil

def check_python():
    """Check if we have a compatible Python version"""
    if sys.version_info < (3, 7):
        print("❌ Python 3.7+ is required. Current version:", sys.version)
        sys.exit(1)
    print(f"✅ Python {sys.version.split()[0]} detected")

def create_env_file():
    """Create config.json file from template if it doesn't exist"""
    if not os.path.exists('config.json'):
        if os.path.exists('config.json.example'):
            shutil.copy('config.json.example', 'config.json')
            print("📄 Created config.json file from template")
            print("\nPlease edit config.json with your Backblaze B2 credentials:")
            print("  - b2.application_key_id: Your B2 application key ID")
            print("  - b2.application_key: Your B2 application key")
            print("  - b2.bucket_name: Your B2 bucket name")
            print("\nYou can get these credentials from your Backblaze account:")
            print("  1. Go to https://secure.backblaze.com/app_keys.htm")
            print("  2. Create a new application key or use an existing one")
            print("  3. Create a bucket or use an existing one")
        else:
            print("❌ config.json.example not found. Creating basic template...")
            basic_config = {
                "b2": {
                    "application_key_id": "your_key_id_here",
                    "application_key": "your_application_key_here",
                    "bucket_name": "your_bucket_name_here"
                },
                "flask": {
                    "host": "127.0.0.1",
                    "port": 8866,
                    "debug": True
                },
                "upload": {
                    "max_file_size_mb": 100,
                    "allowed_extensions": [".jpg", ".jpeg", ".png", ".gif", ".pdf", ".txt", ".doc", ".docx", ".zip", ".mp4", ".mp3"]
                },
                "paste": {
                    "max_length": 1000000
                },
                "security": {
                    "rate_limit_enabled": False,
                    "max_uploads_per_hour": 50
                }
            }
            
            import json
            with open('config.json', 'w') as f:
                json.dump(basic_config, f, indent=2)
            print("📄 Created basic config.json template")
    else:
        print("📄 config.json file already exists. Please ensure it has the correct B2 credentials.")
    
    # Also create .env for backwards compatibility if it doesn't exist
    if not os.path.exists('.env'):
        if os.path.exists('.env.example'):
            shutil.copy('.env.example', '.env')
            print("📄 Also created .env file for backwards compatibility")

def install_dependencies():
    """Install Python dependencies"""
    print("\n📦 Installing Python dependencies...")
    
    if not os.path.exists('requirements.txt'):
        print("❌ requirements.txt not found!")
        return False
    
    # Check if we're in a virtual environment
    in_venv = (hasattr(sys, 'real_prefix') or 
               (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))
    
    if not in_venv:
        print("⚠️  Not in a virtual environment")
        print("Creating virtual environment...")
        try:
            subprocess.run([sys.executable, '-m', 'venv', 'venv'], check=True)
            print("✅ Virtual environment created")
            
            # Determine the correct pip path
            if os.name == 'nt':  # Windows
                pip_path = os.path.join('venv', 'Scripts', 'pip')
                python_path = os.path.join('venv', 'Scripts', 'python')
            else:  # Unix-like
                pip_path = os.path.join('venv', 'bin', 'pip')
                python_path = os.path.join('venv', 'bin', 'python')
            
            # Install dependencies in virtual environment
            subprocess.run([pip_path, 'install', '-r', 'requirements.txt'], check=True)
            print("✅ Dependencies installed in virtual environment")
            print(f"💡 To activate the virtual environment:")
            if os.name == 'nt':
                print("   venv\\Scripts\\activate")
            else:
                print("   source venv/bin/activate")
            print(f"💡 Then run the app with: {python_path} app.py")
            return True
            
        except subprocess.CalledProcessError as e:
            print(f"❌ Failed to create virtual environment or install dependencies: {e}")
            return False
    else:
        print("✅ In virtual environment")
        try:
            subprocess.run([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'], 
                          check=True, capture_output=True, text=True)
            print("✅ Dependencies installed successfully")
            return True
        except subprocess.CalledProcessError as e:
            print(f"❌ Failed to install dependencies: {e}")
            print("Error output:", e.stderr)
            return False

def test_imports():
    """Test if required modules can be imported"""
    print("\n🧪 Testing imports...")
    
    # Check if we're in a virtual environment or if venv was created
    in_venv = (hasattr(sys, 'real_prefix') or 
               (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))
    
    if not in_venv and os.path.exists('venv'):
        print("💡 Skipping import test - using virtual environment")
        print("   Imports will be tested when you activate the virtual environment")
        return True
    
    required_modules = ['flask', 'b2sdk', 'dotenv']
    missing_modules = []
    
    for module in required_modules:
        try:
            __import__(module)
            print(f"  ✅ {module}")
        except ImportError:
            print(f"  ❌ {module}")
            missing_modules.append(module)
    
    if missing_modules:
        print(f"\n❌ Missing modules: {', '.join(missing_modules)}")
        if not in_venv:
            print("💡 This is expected if using a virtual environment")
            return True
        else:
            print("Try running: pip install -r requirements.txt")
            return False
    
    print("✅ All required modules available")
    return True

def check_b2_config():
    """Check if B2 configuration looks valid"""
    print("\n🔧 Checking B2 configuration...")
    
    # Check config.json first
    if os.path.exists('config.json'):
        try:
            import json
            with open('config.json', 'r') as f:
                config_data = json.load(f)
            
            b2_config = config_data.get('b2', {})
            required_keys = ['application_key_id', 'application_key', 'bucket_name']
            invalid_values = ['your_key_id_here', 'your_application_key_here', 'your_bucket_name_here', '']
            missing_keys = []
            
            for key in required_keys:
                value = b2_config.get(key)
                if not value or value in invalid_values:
                    missing_keys.append(f'b2.{key}')
            
            if missing_keys:
                print(f"❌ Please configure these B2 settings in config.json: {', '.join(missing_keys)}")
                return False
            
            print("✅ B2 configuration looks valid in config.json")
            return True
            
        except (json.JSONDecodeError, KeyError) as e:
            print(f"❌ Error reading config.json: {e}")
            return False
    
    # Fall back to .env file
    elif os.path.exists('.env'):
        b2_config = {}
        with open('.env', 'r') as f:
            for line in f:
                line = line.strip()
                if '=' in line and not line.startswith('#'):
                    key, value = line.split('=', 1)
                    b2_config[key] = value
        
        required_keys = ['B2_APPLICATION_KEY_ID', 'B2_APPLICATION_KEY', 'B2_BUCKET_NAME']
        missing_keys = []
        
        for key in required_keys:
            if key not in b2_config or b2_config[key] in ['', 'your_key_id_here', 'your_application_key_here', 'your_bucket_name_here']:
                missing_keys.append(key)
        
        if missing_keys:
            print(f"❌ Please configure these B2 settings in .env: {', '.join(missing_keys)}")
            return False
        
        print("✅ B2 configuration looks valid in .env")
        return True
    
    else:
        print("❌ No configuration file found (config.json or .env)")
        return False

def main():
    """Main setup function"""
    print("🚀 Setting up Sharey with Backblaze B2 Storage...\n")
    
    # Check Python version
    check_python()
    
    # Create .env file
    create_env_file()
    
    # Install dependencies
    if not install_dependencies():
        print("\n❌ Setup failed during dependency installation")
        sys.exit(1)
    
    # Test imports
    if not test_imports():
        print("\n❌ Setup failed: missing required modules")
        sys.exit(1)
    
    # Check B2 configuration
    config_valid = check_b2_config()
    
    print("\n" + "="*60)
    print("🎉 Setup complete!")
    print("="*60)
    
    # Check if we're in a virtual environment
    in_venv = (hasattr(sys, 'real_prefix') or 
               (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))
    
    if not in_venv and os.path.exists('venv'):
        print("\n💡 Virtual environment created!")
        print("To use Sharey:")
        if os.name == 'nt':  # Windows
            print("  1. Activate virtual environment: venv\\Scripts\\activate")
            print("  2. Edit config.json with your B2 credentials")
            print("  3. Test B2 connection: venv\\Scripts\\python test_b2.py")
            print("  4. Run the app: venv\\Scripts\\python app.py")
        else:  # Unix-like
            print("  1. Activate virtual environment: source venv/bin/activate")
            print("  2. Edit config.json with your B2 credentials")
            print("  3. Test B2 connection: python test_b2.py")
            print("  4. Run the app: python app.py")
    else:
        if not config_valid:
            print("\n⚠️  Next steps:")
            print("  1. Edit config.json with your B2 credentials")
            print("  2. Run: python test_b2.py (to test B2 connection)")
            print("  3. Run: python app.py (to start the application)")
        else:
            print("\n✅ Next steps:")
            print("  1. Run: python test_b2.py (to test B2 connection)")
            print("  2. Run: python app.py (to start the application)")
    
    print("\n📋 Notes:")
    print("  - Make sure your B2 bucket allows public downloads")
    print("  - Application will be available at http://127.0.0.1:8866")
    print("  - Check DEPLOYMENT.md for production deployment guide")

if __name__ == "__main__":
    main()
