#!/usr/bin/env python3
"""
Deploy frontend/out to live server: /home/attendancetech2d/public_html/
Preserves protected folders:
  - api.attendance.tech2day.co.in
  - attendanceapi.tech2day.co.in
  - code
  - .htaccess
"""

import os
import sys
import tarfile
import tempfile
import time

try:
    import paramiko
except ImportError:
    print("\n❌ paramiko is not installed in this Python environment.")
    print("Please install paramiko:")
    print("  pip install paramiko\n")
    sys.exit(1)

# Server Configuration
SERVER_IP = "94.136.190.60"
SERVER_USER = "root"
SERVER_PASS = "RavindraChinnu12@"
TARGET_USER = "attendancetech2d"
TARGET_DIR = f"/home/{TARGET_USER}/public_html"

PRESERVED_ITEMS = [
    "api.attendance.tech2day.co.in",
    "attendanceapi.tech2day.co.in",
    "code",
    ".htaccess",
    "downloads",
    "files",
    "uploads",
]

def find_out_dir():
    candidates = [
        os.path.abspath(os.path.join(os.path.dirname(__file__), "../out")),
        os.path.abspath("./out"),
        os.path.abspath("./frontend/out"),
    ]
    for c in candidates:
        if os.path.isdir(c) and os.path.exists(os.path.join(c, "index.html")):
            return c
    return None

def create_archive(out_dir, tar_path):
    print(f"📦 Compressing {out_dir} into archive...")
    start = time.time()
    with tarfile.open(tar_path, "w:gz") as tar:
        for root, dirs, files in os.walk(out_dir):
            for file in files:
                full_path = os.path.join(root, file)
                rel_path = os.path.relpath(full_path, out_dir)
                tar.add(full_path, arcname=rel_path)
    size_mb = os.path.getsize(tar_path) / (1024 * 1024)
    print(f"✅ Archive created: {tar_path} ({size_mb:.2f} MB in {time.time() - start:.1f}s)")

def main():
    print("=" * 60)
    print("🚀 IHM Kolkata Attendance Web App Live Server Deployment")
    print(f"📍 Target: {TARGET_USER}@{SERVER_IP}:{TARGET_DIR}/")
    print(f"🛡️  Preserving: {', '.join(PRESERVED_ITEMS)}")
    print("=" * 60)

    out_dir = find_out_dir()
    if not out_dir:
        print("\n❌ Error: Could not find 'out' folder with index.html.")
        print("Please build your project first:")
        print("  cd frontend && npm run build\n")
        sys.exit(1)

    print(f"📂 Found export directory: {out_dir}")

    temp_archive = os.path.join(tempfile.gettempdir(), f"ihm_out_{int(time.time())}.tar.gz")

    try:
        create_archive(out_dir, temp_archive)

        print(f"\n🔌 Connecting via SSH to {SERVER_USER}@{SERVER_IP}...")
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(SERVER_IP, username=SERVER_USER, password=SERVER_PASS, timeout=30)
        print("✅ SSH Connected.")

        remote_archive = "/tmp/ihm_out_deploy.tar.gz"
        print(f"⬆️  Uploading web archive via SFTP to {remote_archive}...")
        sftp = client.open_sftp()

        def progress(transferred, total):
            pct = (transferred / total) * 100 if total else 0
            mb_trans = transferred / (1024 * 1024)
            mb_tot = total / (1024 * 1024)
            sys.stdout.write(f"\r   Progress: {pct:5.1f}% ({mb_trans:.1f}/{mb_tot:.1f} MB)")
            sys.stdout.flush()

        sftp.put(temp_archive, remote_archive, callback=progress)
        print("\n✅ Web bundle upload completed.")
        sftp.close()

        # Build safe find exclusion command to avoid deleting preserved folders
        exclude_args = " ".join([f'! -name "{item}"' for item in PRESERVED_ITEMS])
        clean_cmd = f'find {TARGET_DIR} -mindepth 1 -maxdepth 1 {exclude_args} -exec rm -rf {{}} +'

        commands = [
            # Ensure target directory exists
            f"mkdir -p {TARGET_DIR}",
            # Remove old files/folders except preserved ones
            clean_cmd,
            # Extract new out files
            f"tar -xzf {remote_archive} -C {TARGET_DIR}/",
            # Remove uploaded tarball
            f"rm -f {remote_archive}",
            # Fix ownership and permissions for the target user
            f"chown -R {TARGET_USER}:{TARGET_USER} {TARGET_DIR}/ 2>/dev/null || true",
            f"chmod -R 755 {TARGET_DIR}/ 2>/dev/null || true",
            # Show summary
            f"echo '--- Deployment directory contents ---'",
            f"ls -la {TARGET_DIR}/ | head -n 35",
        ]

        full_cmd = " && ".join(commands)
        print("\n⚙️  Cleaning old files (preserving protected folders) and extracting new release...")
        stdin, stdout, stderr = client.exec_command(full_cmd, timeout=180)

        for line in stdout:
            print(line, end="")

        err = stderr.read().decode()
        if err:
            print("\n[Server Output / Warnings]:\n", err)

        print("\n" + "=" * 60)
        print("✅ Attendance Web App live deployment completed successfully!")
        print("🌐 Live Portal:     https://attendance.tech2day.co.in/")
        print("🌐 API Endpoint:    https://attendanceapi.tech2day.co.in/")
        print("=" * 60)

    finally:
        if os.path.exists(temp_archive):
            os.remove(temp_archive)
        try:
            client.close()
        except:
            pass

if __name__ == "__main__":
    main()
