#!/usr/bin/env python3
"""
FTP Upload Script for Fly Nav Mobile Plugin
Uploads all plugin files to the test WordPress site
"""

import ftplib
import os

# FTP Configuration
FTP_HOST = "198.54.116.105"
FTP_USER = "aamir@plugintest2.xyz"
FTP_PASS = "Aamir.8878.9200"
REMOTE_BASE_PATH = "/wp-content/plugins/fly-nav-mobile"

# Local plugin directory (same as script location)
LOCAL_DIR = os.path.dirname(os.path.abspath(__file__))

# Files and directories to upload
FILES_TO_UPLOAD = [
    "fly-nav-mobile.php",
    "readme.txt",
    "uninstall.php",
]

DIRECTORIES_TO_UPLOAD = [
    "includes",
    "backend",
    "public",
    "assets",
]

def create_remote_dir(ftp, path):
    """Create remote directory if it doesn't exist"""
    dirs = path.split('/')
    current = ""
    for d in dirs:
        if not d:
            continue
        current += "/" + d
        try:
            ftp.cwd(current)
        except ftplib.error_perm:
            try:
                ftp.mkd(current)
                print(f"  Created directory: {current}")
            except ftplib.error_perm:
                pass

def upload_file(ftp, local_path, remote_path):
    """Upload a single file"""
    try:
        with open(local_path, 'rb') as f:
            ftp.storbinary(f'STOR {remote_path}', f)
        print(f"  ✓ Uploaded: {os.path.basename(local_path)}")
        return True
    except Exception as e:
        print(f"  ✗ Failed: {os.path.basename(local_path)} - {e}")
        return False

def upload_directory(ftp, local_dir, remote_dir):
    """Recursively upload a directory"""
    create_remote_dir(ftp, remote_dir)
    
    for item in os.listdir(local_dir):
        local_path = os.path.join(local_dir, item)
        remote_path = f"{remote_dir}/{item}"
        
        # Skip hidden files and .DS_Store
        if item.startswith('.'):
            continue
            
        if os.path.isdir(local_path):
            upload_directory(ftp, local_path, remote_path)
        else:
            upload_file(ftp, local_path, remote_path)

def main():
    print("=" * 50)
    print("Fly Nav Mobile FTP Upload")
    print("=" * 50)
    print(f"Host: {FTP_HOST}")
    print(f"Remote Path: {REMOTE_BASE_PATH}")
    print("=" * 50)
    
    try:
        # Connect to FTP
        print("\nConnecting to FTP server...")
        ftp = ftplib.FTP(FTP_HOST)
        ftp.login(FTP_USER, FTP_PASS)
        print("✓ Connected successfully!\n")
        
        # Create base plugin directory
        create_remote_dir(ftp, REMOTE_BASE_PATH)
        
        # Upload individual files
        print("Uploading files...")
        for file in FILES_TO_UPLOAD:
            local_path = os.path.join(LOCAL_DIR, file)
            if os.path.exists(local_path):
                remote_path = f"{REMOTE_BASE_PATH}/{file}"
                upload_file(ftp, local_path, remote_path)
            else:
                print(f"  ⚠ Skipped (not found): {file}")
        
        # Upload directories
        print("\nUploading directories...")
        for directory in DIRECTORIES_TO_UPLOAD:
            local_path = os.path.join(LOCAL_DIR, directory)
            if os.path.isdir(local_path):
                print(f"\n  [{directory}]")
                remote_path = f"{REMOTE_BASE_PATH}/{directory}"
                upload_directory(ftp, local_path, remote_path)
            else:
                print(f"  ⚠ Skipped (not found): {directory}/")
        
        # Close connection
        ftp.quit()
        
        print("\n" + "=" * 50)
        print("✓ Upload complete!")
        print("=" * 50)
        print(f"\nTest site: https://plugintest2.xyz/wp-admin/plugins.php")
        
    except ftplib.all_errors as e:
        print(f"\n✗ FTP Error: {e}")
        return 1
    
    return 0

if __name__ == "__main__":
    exit(main())
