import paramiko
import os
from deezer_downloader.configuration import config

def call_scan(directory_path):
    if not config['nextcloud_ssh_scan_files']['host']:
        return
    host = config['nextcloud_ssh_scan_files']['host']
    port = config['nextcloud_ssh_scan_files']['port']
    username = config['nextcloud_ssh_scan_files']['username']
    password = config['nextcloud_ssh_scan_files']['password']
    occCmd= config['nextcloud_ssh_scan_files']['occ_path']

    if isinstance(directory_path, (list, tuple)) and all(isinstance(x, str) for x in directory_path):
        directory_path = directory_path[0]
    directory_path = os.path.dirname(directory_path)
    directory_path = directory_path.replace(config['download_dirs']['base'], "").lstrip("/\\")
    print("Path Nexcloud Scan " + directory_path)
    
    # Commande à exécuter
    cmd = "sudo -u www-data php {occ} files:scan --path='{dir}'".format(occ= occCmd,dir=directory_path)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  # accepter clés inconnues
    ssh.connect(hostname=host, port=port, username=username, password=password)

    # Exécuter la commande
    stdin, stdout, stderr = ssh.exec_command(cmd)

    # Afficher les résultats
    print("STDOUT:")
    print(stdout.read().decode())

    print("STDERR:")
    print(stderr.read().decode())

    # Fermer la connexion
    ssh.close()