import subprocess
import os


def setup_and_mount_virtual_drive():
    base_dir = r"C:\Images"
    os.makedirs(base_dir, exist_ok=True)

    # Using .vhdx for native Windows mounting and formatting support
    vhdx_path = os.path.join(base_dir, "virtual_disk_1gb.vhdx")

    # PowerShell script to create, mount, partition, format, and assign a drive letter
    ps_script = f"""
    $vhdPath = "{vhdx_path}"
    if (!(Test-Path $vhdPath)) {{
        New-VHD -Path $vhdPath -SizeBytes 1GB -Fixed | Out-Null
    }}

    # Check if already mounted
    $diskImage = Get-DiskImage -ImagePath $vhdPath -ErrorAction SilentlyContinue
    if (-not $diskImage.Attached) {{
        $diskImage = Mount-VHD -Path $vhdPath -PassThru
    }}

    $disk = $diskImage | Get-Disk
    $partition = $disk | Get-Partition -ErrorAction SilentlyContinue

    if (-not $partition -or -not $partition.DriveLetter) {{
        Initialize-Disk -Number $disk.Number -PartitionStyle GPT -ErrorAction SilentlyContinue
        $partition = New-Partition -DiskNumber $disk.Number -UseMaximumSize -AssignDriveLetter
        Format-Volume -Partition $partition -FileSystem NTFS -NewFileSystemLabel "VirtualData" -Confirm:$false | Out-Null
    }}

    # Output the assigned drive letter
    $vol = $partition | Get-Volume
    Write-Output "$($vol.DriveLetter):"
    """

    print("Configuring and mounting virtual disk via PowerShell...")
    result = subprocess.run(["powershell", "-Command", ps_script], capture_output=True, text=True)

    if result.returncode != 0:
        print(f"Error during mounting: {result.stderr.strip()}")
        return

    # Parse the drive letter from PowerShell output
    output_lines = [line.strip() for line in result.stdout.splitlines() if line.strip()]
    drive_letter = output_lines[-1] if output_lines else None

    if not drive_letter or len(drive_letter) < 2:
        print("Failed to retrieve drive letter for the virtual disk.")
        return

    print(f"Virtual disk successfully mounted at: {drive_letter}")

    # Create the four folders inside the mounted virtual drive
    folders = [
        "filingCabinet",
        "localStorage",
        "localScripts",
        "localBackups"
    ]

    for folder in folders:
        folder_path = os.path.join(f"{drive_letter}\\", folder)
        os.makedirs(folder_path, exist_ok=True)
        print(f"Created folder inside virtual drive: {folder_path}")


if __name__ == "__main__":
    setup_and_mount_virtual_drive()