import { exec } from 'child_process';
import { promisify } from 'util';
import os from 'os';
import { g as getBackupsDir } from '../../auth/setup/POST-DYMc2GPx.js';

const execAsync = promisify(exec);
async function handler(req, res) {
  try {
    const backupsDir = getBackupsDir();
    const platform = os.platform();
    let diskSpace = {
      total: 0,
      used: 0,
      free: 0,
      percentUsed: 0
    };
    if (platform === "win32") {
      try {
        const drive = backupsDir.charAt(0);
        const { stdout } = await execAsync(`wmic logicaldisk where "DeviceID='${drive}:'" get Size,FreeSpace /format:csv`);
        const lines = stdout.trim().split("\n");
        if (lines.length >= 2) {
          const parts = lines[1].split(",");
          const free = parseInt(parts[1]) || 0;
          const total = parseInt(parts[2]) || 0;
          diskSpace = {
            total,
            used: total - free,
            free,
            percentUsed: total > 0 ? (total - free) / total * 100 : 0
          };
        }
      } catch (error) {
        console.error("Failed to get Windows disk space:", error);
      }
    } else {
      try {
        const { stdout } = await execAsync(`df -k "${backupsDir}" | tail -1`);
        const parts = stdout.trim().split(/\s+/);
        if (parts.length >= 6) {
          const total = parseInt(parts[1]) * 1024;
          const used = parseInt(parts[2]) * 1024;
          const free = parseInt(parts[3]) * 1024;
          diskSpace = {
            total,
            used,
            free,
            percentUsed: total > 0 ? used / total * 100 : 0
          };
        }
      } catch (error) {
        console.error("Failed to get Unix disk space:", error);
      }
    }
    res.json(diskSpace);
  } catch (error) {
    console.error("Failed to get disk space:", error);
    res.status(500).json({
      success: false,
      error: "Failed to get disk space information",
      message: String(error)
    });
  }
}

export { handler as h };
