import { exec } from 'child_process';
import { promisify } from 'util';
import os from 'os';

const execAsync = promisify(exec);
async function handler(req, res) {
  try {
    const platform = os.platform();
    const drives = [];
    if (platform === "win32") {
      try {
        const { stdout } = await execAsync("wmic logicaldisk get name,size,freespace,volumename /format:csv");
        const lines = stdout.split("\n").filter((line) => line.trim() && !line.startsWith("Node"));
        for (const line of lines) {
          const parts = line.split(",").map((p) => p.trim());
          if (parts.length >= 4 && parts[2]) {
            const freeSpace = parseInt(parts[1]) || 0;
            const name = parts[2];
            const totalSpace = parseInt(parts[3]) || 0;
            const volumeName = parts[4] || "";
            if (totalSpace > 0) {
              const usedSpace = totalSpace - freeSpace;
              drives.push({
                path: name,
                label: volumeName ? `${name} (${volumeName})` : name,
                totalSpace,
                freeSpace,
                usedSpace,
                percentUsed: Math.round(usedSpace / totalSpace * 100)
              });
            }
          }
        }
      } catch (error) {
        console.error("Failed to get Windows drives:", error);
      }
    } else {
      try {
        const { stdout } = await execAsync("df -B1 --output=source,target,size,used,avail,pcent 2>/dev/null || df -k | tail -n +2");
        const lines = stdout.split("\n").filter((line) => line.trim());
        for (const line of lines) {
          const parts = line.split(/\s+/);
          if (parts.length >= 6) {
            const source = parts[0];
            const mountPoint = parts[1];
            if (source.startsWith("/dev/") && !source.includes("loop")) {
              const totalSpace = parseInt(parts[2]) || 0;
              const usedSpace = parseInt(parts[3]) || 0;
              const freeSpace = parseInt(parts[4]) || 0;
              const percentUsed = parseInt(parts[5]) || 0;
              if (totalSpace > 0) {
                drives.push({
                  path: mountPoint,
                  label: `${mountPoint} (${source})`,
                  totalSpace: totalSpace * 1024,
                  // Convert KB to bytes
                  freeSpace: freeSpace * 1024,
                  usedSpace: usedSpace * 1024,
                  percentUsed
                });
              }
            }
          }
        }
      } catch (error) {
        console.error("Failed to get Linux/macOS drives:", error);
      }
    }
    if (drives.length === 0) {
      drives.push({
        path: process.cwd(),
        label: "Current Directory",
        totalSpace: 0,
        freeSpace: 0,
        usedSpace: 0,
        percentUsed: 0
      });
    }
    res.json({ drives });
  } catch (error) {
    console.error("Error getting drives:", error);
    res.status(500).json({ error: "Failed to get drive information" });
  }
}

export { handler as h };
