#!/usr/bin/env python3
"""
Integration Hub - SFTP Deploy Script
Uploads project to cPanel via SFTP
"""

import paramiko
import os
import sys
from pathlib import Path
from datetime import datetime

# Configuration
SFTP_HOST = "ftp.eunecto.com.br"
SFTP_PORT = 1157
SFTP_USER = "eune6179"
SFTP_PASS = "*Vm04021994"
REMOTE_PATH = "/nucleoapi.eunecto.com.br"
LOCAL_PROJECT = "."

# Files to ignore
IGNORE_PATTERNS = {
    '.git',
    '.vscode',
    '.env.example',
    'docker-compose.yml',
    'Dockerfile',
    'docker',
    'node_modules',
    '.DS_Store',
    '__pycache__',
    '*.pyc',
    '.phpunit.result.cache',
    'composer.lock',
}

class SFTPUploader:
    def __init__(self, host, port, username, password):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.ssh = None
        self.sftp = None
        self.uploaded_count = 0
        self.failed_count = 0

    def connect(self):
        """Connect to SFTP server"""
        try:
            print(f"🔗 Connecting to {self.host}:{self.port}...")
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(
                self.host,
                port=self.port,
                username=self.username,
                password=self.password,
                timeout=30
            )
            self.sftp = self.ssh.open_sftp()
            print("✅ Connected successfully!")
            return True
        except Exception as e:
            print(f"❌ Connection failed: {e}")
            return False

    def should_ignore(self, path):
        """Check if path should be ignored"""
        parts = path.split(os.sep)
        for part in parts:
            if part in IGNORE_PATTERNS:
                return True
            for pattern in IGNORE_PATTERNS:
                if pattern.startswith('*.'):
                    ext = pattern[1:]
                    if part.endswith(ext):
                        return True
        return False

    def ensure_remote_dir(self, remote_path):
        """Create remote directory if it doesn't exist"""
        try:
            self.sftp.stat(remote_path)
        except IOError:
            try:
                self.sftp.mkdir(remote_path)
                print(f"  📁 Created directory: {remote_path}")
            except Exception as e:
                print(f"  ⚠️  Could not create {remote_path}: {e}")

    def upload_file(self, local_file, remote_file):
        """Upload a single file"""
        try:
            self.sftp.put(local_file, remote_file)
            self.uploaded_count += 1
            return True
        except Exception as e:
            print(f"  ❌ Failed to upload {remote_file}: {e}")
            self.failed_count += 1
            return False

    def upload_directory(self, local_dir, remote_dir):
        """Recursively upload directory"""
        print(f"\n📤 Uploading {local_dir}...")

        for root, dirs, files in os.walk(local_dir):
            # Filter directories
            dirs[:] = [d for d in dirs if not self.should_ignore(d)]

            # Get relative path
            rel_path = os.path.relpath(root, local_dir)
            if rel_path == ".":
                current_remote = remote_dir
            else:
                current_remote = f"{remote_dir}/{rel_path}".replace('\\', '/')

            # Create remote directory
            self.ensure_remote_dir(current_remote)

            # Upload files
            for file in files:
                if self.should_ignore(file):
                    continue

                local_file = os.path.join(root, file)
                remote_file = f"{current_remote}/{file}".replace('\\', '/')

                sys.stdout.write(f"\r  ⬆️  {file:<50} [{self.uploaded_count}]")
                sys.stdout.flush()

                self.upload_file(local_file, remote_file)

        print()

    def upload_all(self):
        """Upload entire project"""
        print("\n" + "="*60)
        print("🚀 Integration Hub - SFTP Deployment")
        print("="*60)

        if not self.connect():
            return False

        # Upload main project
        self.upload_directory(".", REMOTE_PATH)

        # Summary
        print("\n" + "="*60)
        print("📊 Upload Summary")
        print("="*60)
        print(f"✅ Files uploaded:  {self.uploaded_count}")
        print(f"❌ Files failed:    {self.failed_count}")
        print(f"🕐 Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("="*60)

        # Disconnect
        try:
            self.sftp.close()
            self.ssh.close()
            print("✅ Disconnected")
        except:
            pass

        return self.failed_count == 0

if __name__ == "__main__":
    uploader = SFTPUploader(SFTP_HOST, SFTP_PORT, SFTP_USER, SFTP_PASS)
    success = uploader.upload_all()

    if success:
        print("\n✅ DEPLOYMENT SUCCESSFUL!")
        print("\n📝 Next steps:")
        print("1. Access cPanel and run the deploy.sh script:")
        print("   cd ~/nucleoapi.eunecto.com.br && bash deploy.sh")
        print("\n2. Or via SSH:")
        print("   ssh eune6179@ftp.eunecto.com.br -p 1157")
        sys.exit(0)
    else:
        print("\n⚠️  DEPLOYMENT COMPLETED WITH ERRORS")
        sys.exit(1)
