const express      = require('express');
const { execSync } = require('child_process');
const router       = express.Router();
const authMw       = require('../middleware/auth');

const ps = (script) => execSync(
  `powershell -ExecutionPolicy Bypass -File "${__dirname}/../scripts/${script}"`,
  { timeout: 15000 }
).toString().trim();

function parseCpu(raw) {
  const val = parseInt(raw, 10);
  return isNaN(val) ? 0 : Math.min(100, Math.max(0, val));
}
function parseRam(raw) {
  const parts = raw.split(/\s+/).map(Number);
  if (parts.length < 2 || isNaN(parts[0]) || isNaN(parts[1]))
    return { used: 0, total: 0 };
  return { used: parts[0], total: parts[1] };
}
function parseDisks(raw) {
  if (!raw) return [];
  return raw.split('\n')
    .map(line => line.trim()).filter(Boolean)
    .map(line => {
      const parts = line.split(/\s+/);
      if (parts.length < 3) return null;
      const [label, used, total] = parts;
      const u = parseFloat(used), t = parseFloat(total);
      if (isNaN(u) || isNaN(t) || t === 0) return null;
      return { label, used: u, total: t };
    }).filter(Boolean);
}
function parseNetwork(raw) {
  const parts = raw.split(/\s+/).map(Number);
  if (parts.length < 2 || isNaN(parts[0]) || isNaN(parts[1]))
    return { sent: 0, received: 0 };
  return { sent: parts[0], received: parts[1] };
}

function collectStats() {
  const result = {
    cpu:     0,
    ram:     { used: 0, total: 0 },
    disks:   [],
    network: { sent: 0, received: 0 }
  };
  try { result.cpu     = parseCpu(ps('getCpuUsage.ps1'));      } catch(e) { console.error('[cpu]', e.message); }
  try { result.ram     = parseRam(ps('getRamUsage.ps1'));      } catch(e) { console.error('[ram]', e.message); }
  try { result.disks   = parseDisks(ps('getDiskUsage.ps1'));   } catch(e) { console.error('[disk]', e.message); }
  try { result.network = parseNetwork(ps('getNetworkIO.ps1')); } catch(e) { console.error('[net]', e.message); }
  return result;
}

router.get('/stats', authMw, (req, res) => {
  try {
    res.json(collectStats());
  } catch(e) {
    res.status(500).json({ error: e.message });
  }
});

module.exports = router;
module.exports.collectStats = collectStats;