"""
Installation script for the DecentraBrowser system.
"""
import os
import sys
import argparse
import subprocess
import platform
import shutil
from pathlib import Path

def check_python_version():
    """Check that Python version is at least 3.8."""
    if sys.version_info < (3, 8):
        print("Error: Python 3.8 or higher is required")
        sys.exit(1)

def install_dependencies():
    """Install Python dependencies."""
    print("Installing dependencies...")
    
    # Install requirements
    subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
    
    print("Dependencies installed successfully")

def create_data_directory():
    """Create data directory."""
    home = Path.home()
    
    if platform.system() == "Windows":
        data_dir = home / "AppData" / "Local" / "DecentraBrowser"
    elif platform.system() == "Darwin":
        data_dir = home / "Library" / "Application Support" / "DecentraBrowser"
    else:
        data_dir = home / ".decentrabrowser"
    
    # Create directories
    os.makedirs(data_dir, exist_ok=True)
    os.makedirs(data_dir / "certs", exist_ok=True)
    os.makedirs(data_dir / "content", exist_ok=True)
    os.makedirs(data_dir / "downloads", exist_ok=True)
    
    print(f"Data directory created at {data_dir}")
    
    return data_dir

def create_desktop_shortcut(install_dir):
    """Create desktop shortcut."""
    home = Path.home()
    desktop = home / "Desktop"
    
    if platform.system() == "Windows":
        # Create Windows shortcut
        shortcut_path = desktop / "DecentraBrowser.lnk"
        
        # Use Windows script to create shortcut
        vbs_script = """
        Set oWS = WScript.CreateObject("WScript.Shell")
        sLinkFile = "{0}"
        Set oLink = oWS.CreateShortcut(sLinkFile)
        oLink.TargetPath = "{1}"
        oLink.Save
        """.format(str(shortcut_path), str(install_dir / "run.bat"))
        
        with open("create_shortcut.vbs", "w") as f:
            f.write(vbs_script)
        
        subprocess.call(["cscript", "create_shortcut.vbs"])
        os.remove("create_shortcut.vbs")
        
    elif platform.system() == "Darwin":
        # Create macOS .command file
        command_path = desktop / "DecentraBrowser.command"
        
        with open(command_path, "w") as f:
            f.write(f"#!/bin/bash\ncd {install_dir} && python -m decentrabrowser.client.app")
        
        # Make executable
        os.chmod(command_path, 0o755)
        
    else:
        # Create Linux .desktop file
        desktop_file = """
        [Desktop Entry]
        Version=1.0
        Type=Application
        Name=DecentraBrowser
        Comment=Decentralized Browser
        Exec=python -m decentrabrowser.client.app
        Path={0}
        Terminal=false
        Categories=Network;
        """.format(str(install_dir))
        
        desktop_path = desktop / "DecentraBrowser.desktop"
        
        with open(desktop_path, "w") as f:
            f.write(desktop_file)
        
        # Make executable
        os.chmod(desktop_path, 0o755)
    
    print(f"Desktop shortcut created at {desktop}")

def create_startup_scripts(install_dir):
    """Create startup scripts."""
    if platform.system() == "Windows":
        # Create batch file
        bat_path = install_dir / "run.bat"
        
        with open(bat_path, "w") as f:
            f.write(f"@echo off\ncd {install_dir}\npython -m decentrabrowser.client.app")
        
    elif platform.system() == "Darwin" or platform.system() == "Linux":
        # Create shell script
        sh_path = install_dir / "run.sh"
        
        with open(sh_path, "w") as f:
            f.write(f"#!/bin/bash\ncd {install_dir} && python -m decentrabrowser.client.app")
        
        # Make executable
        os.chmod(sh_path, 0o755)
    
    print("Startup scripts created")

def main():
    """Main installation function."""
    parser = argparse.ArgumentParser(description="DecentraBrowser Installation Script")
    parser.add_argument("--install-dir", type=str, default=None,
                        help="Installation directory (default: current directory)")
    parser.add_argument("--no-shortcut", action="store_true",
                        help="Don't create desktop shortcut")
    
    args = parser.parse_args()
    
    print("DecentraBrowser Installation")
    print("===========================")
    
    # Check Python version
    check_python_version()
    
    # Determine installation directory
    if args.install_dir:
        install_dir = Path(args.install_dir)
    else:
        install_dir = Path.cwd()
    
    print(f"Installing to: {install_dir}")
    
    # Install dependencies
    install_dependencies()
    
    # Create data directory
    data_dir = create_data_directory()
    
    # Create startup scripts
    create_startup_scripts(install_dir)
    
    # Create desktop shortcut
    if not args.no_shortcut:
        create_desktop_shortcut(install_dir)
    
    print("\nInstallation Complete!")
    print(f"To start DecentraBrowser, run: python -m decentrabrowser.client.app")

if __name__ == "__main__":
    main()