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

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

// ── Parsers ────────────────────────────────────────────

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);
      const 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] };
}

// ── Shared collector (used by REST route + WebSocket) ──
function collectStats() {
  const result = {
    cpu:      0,
    ram:      { used: 0, total: 0 },
    disks:    [],
    network:  { sent: 0, received: 0 },
    warnings: []
  };

  try { result.cpu     = parseCpu(ps('getCpuUsage.ps1'));      } catch (e) { result.warnings.push('cpu: '     + e.message); }
  try { result.ram     = parseRam(ps('getRamUsage.ps1'));      } catch (e) { result.warnings.push('ram: '     + e.message); }
  try { result.disks   = parseDisks(ps('getDiskUsage.ps1'));   } catch (e) { result.warnings.push('disks: '   + e.message); }
  try { result.network = parseNetwork(ps('getNetworkIO.ps1')); } catch (e) { result.warnings.push('network: ' + e.message); }

  if (result.warnings.length === 0) delete result.warnings;
  return result;
}

// ── REST route ─────────────────────────────────────────
router.get('/stats', authMw, (req, res) => {
  sCache('system.stats', 3000, collectStats)
    .then(data => res.json(data))
    .catch(e => res.status(500).json({ error: e.message }));
});

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