import os
import shutil

def get_non_c_drive() -> str:
    """
    Find the first available non-C drive on the target system.
    """
    possible_drives = [f"{letter}:\\" for letter in "DEFGH"]
    for drive in possible_drives:
        if os.path.exists(drive):
            return drive
    return r"C:\\"

def setup_directories_and_copy(source_dir: str = r"C:\SoftwareNP", 
                               target_drive: str = None) -> str:
    """
    Create directories on a non-C drive and copy files from source to NovinSoft.
    """
    if not target_drive:
        base_drive = get_non_c_drive()
    else:
        base_drive = target_drive

    # Base target directory set to NovinPardazOne
    base_target_dir = os.path.join(base_drive, "NovinPardazOne")
    acc_dir = os.path.join(base_target_dir, "NovinAcc")
    soft_dir = os.path.join(base_target_dir, "NovinSoft")

    print(f"[+] Selected target drive: {base_drive}")
    print(f"[+] Creating directory structure at {base_target_dir} ...")

    # Create NovinAcc and NovinSoft directories
    os.makedirs(acc_dir, exist_ok=True)
    os.makedirs(soft_dir, exist_ok=True)
    print("  [+] NovinAcc and NovinSoft directories created successfully.")

    # Copy contents of source directory to NovinSoft
    if os.path.exists(source_dir):
        print(f"[+] Copying files from {source_dir} to {soft_dir} ...")
        
        for item in os.listdir(source_dir):
            s = os.path.join(source_dir, item)
            d = os.path.join(soft_dir, item)
            
            if os.path.isdir(s):
                shutil.copytree(s, d, dirs_exist_ok=True)
            else:
                shutil.copy2(s, d)
                
        print(f"  [+] All files copied successfully to {soft_dir}.")
        return soft_dir
    else:
        raise FileNotFoundError(f"[-] Source directory not found at {source_dir}!")

if __name__ == "__main__":
    os.system("chcp 65001 > nul")
    print("[+] Testing directory creation and software copy module ...")

    try:
        target_path = setup_directories_and_copy(target_drive=r"D:\\")
        print(f"\n[+] Operation completed successfully. Software path: {target_path}")
    except Exception as e:
        print(f"\n[-] Error: {e}")
