import os
import glob
import subprocess
from config import RUNNING_ON_MAIN_SERVER, VM_HOST, VM_PORT, VM_KEY, VM_USER, MAIN_SERVER_IP


def run_command(cmd):
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=30)
        return result.stdout, result.stderr
    except Exception as e:
        return '', str(e)


def get_local_backups():
    """
    On main server → /root/backups/  (backups of the main server, stored locally)
    On VM          → /backups/main-server/  (backups of the main server, stored on VM)
    """
    if RUNNING_ON_MAIN_SERVER:
        path = "/root/backups/myapps-backup-*.tar.gz"
    else:
        path = "/backups/main-server/myapps-backup-*.tar.gz"

    stdout, _ = run_command(f"ls -t {path} 2>/dev/null | head -20")
    files = []
    if stdout:
        for line in stdout.strip().split('\n'):
            line = line.strip()
            if line:
                files.append(os.path.basename(line))
    return files


def get_vm_backups():
    """
    On main server → SSH into VM (via tunnel port 2223) to list /backups/main-server/
    On VM          → SSH into main server (port 22) to list /root/backups/
    """
    backups = []

    if RUNNING_ON_MAIN_SERVER:
        # Original logic — unchanged
        try:
            cmd = (
                f"ssh -i {VM_KEY} -p {VM_PORT} "
                f"-o StrictHostKeyChecking=no -o ConnectTimeout=10 "
                f"{VM_USER}@{VM_HOST} "
                f"'ls -t /backups/main-server/myapps-backup-*.tar.gz 2>/dev/null | head -20'"
            )
            stdout, _ = run_command(cmd)
            if stdout:
                for line in stdout.strip().split('\n'):
                    line = line.strip()
                    if line and '.tar.gz' in line:
                        backups.append(os.path.basename(line))
        except Exception as e:
            print(f"[backups] Error fetching VM backups: {e}")

    else:
        # Running on VM → SSH into main server to list its local backups
        try:
            cmd = (
                f"ssh -i {VM_KEY} -p 22 "
                f"-o StrictHostKeyChecking=no -o ConnectTimeout=10 "
                f"{VM_USER}@{MAIN_SERVER_IP} "
                f"'ls -t /root/backups/myapps-backup-*.tar.gz 2>/dev/null | head -20'"
            )
            stdout, _ = run_command(cmd)
            if stdout:
                for line in stdout.strip().split('\n'):
                    line = line.strip()
                    if line and '.tar.gz' in line:
                        backups.append(os.path.basename(line))
        except Exception as e:
            print(f"[backups] Error fetching main server backups from VM: {e}")

    return backups


def get_containers():
    """
    On main server → local docker ps  (original, unchanged)
    On VM          → SSH into main server to get its containers
    """
    if RUNNING_ON_MAIN_SERVER:
        stdout, _ = run_command(
            "docker ps -a --format '{{.Names}}|{{.Status}}' 2>/dev/null"
        )
    else:
        cmd = (
            f"ssh -i {VM_KEY} -p 22 "
            f"-o StrictHostKeyChecking=no -o ConnectTimeout=10 "
            f"{VM_USER}@{MAIN_SERVER_IP} "
            f"\"docker ps -a --format '{{{{.Names}}}}|{{{{.Status}}}}' 2>/dev/null\""
        )
        stdout, _ = run_command(cmd)

    containers = []
    if stdout:
        for line in stdout.strip().split('\n'):
            if '|' in line:
                name, status = line.split('|', 1)
                containers.append({'name': name.strip(), 'status': status.strip()})
    return containers
