const express = require('express');
const router = express.Router();
const { exec } = require('child_process');
const fs = require('fs');

/**
 * About Module — Trinity Console
 * 
 * Console version, module versions, deploy button, system meta.
 * 
 * GET  /admin/about          — About page
 * POST /admin/about/deploy   — Deploy Arbiter (moved from sidebar)
 * GET  /admin/about/status   — Arbiter health check
 * 
 * Chronicler #78 | April 11, 2026
 */

const MODULES = [
  { name: 'Dashboard', version: '1.0.0', path: '/admin/dashboard', icon: '📊', status: 'stable' },
  { name: 'Tasks', version: '1.0.0', path: '/admin/tasks', icon: '📋', status: 'new' },
  { name: 'Servers', version: '1.0.0', path: '/admin/servers', icon: '🖥️', status: 'stable' },
  { name: 'Players', version: '1.0.0', path: '/admin/players', icon: '👥', status: 'stable' },
  { name: 'Financials', version: '1.0.0', path: '/admin/financials', icon: '💰', status: 'stable' },
  { name: 'Grace Period', version: '1.0.0', path: '/admin/grace', icon: '⏳', status: 'stable' },
  { name: 'Discord', version: '1.0.0', path: '/admin/discord', icon: '💬', status: 'stable' },
  { name: 'Social', version: '1.0.0', path: '/admin/social', icon: '📈', status: 'stable' },
  { name: 'Infrastructure', version: '1.0.0', path: '/admin/infrastructure', icon: '🌐', status: 'new' },
  { name: 'Restart Scheduler', version: '1.0.0', path: '/admin/scheduler', icon: '⏰', status: 'stable' },
  { name: 'Audit Log', version: '1.0.0', path: '/admin/audit', icon: '📋', status: 'stable' },
  { name: 'Role Audit', version: '1.0.0', path: '/admin/roles', icon: '🔍', status: 'stable' },
  { name: 'MCP Logs', version: '1.0.0', path: '/admin/mcp-logs', icon: '🖥️', status: 'new' },
];

function getNodeVersion() {
  return process.version;
}

function getArbiterUptime() {
  return process.uptime();
}

function formatUptime(seconds) {
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const mins = Math.floor((seconds % 3600) / 60);
  if (days > 0) return `${days}d ${hours}h ${mins}m`;
  if (hours > 0) return `${hours}h ${mins}m`;
  return `${mins}m`;
}

// GET /admin/about
router.get('/', (req, res) => {
  const pkg = JSON.parse(fs.readFileSync(require.resolve('../../../package.json'), 'utf8'));

  res.render('admin/about/index', {
    title: 'About',
    currentPath: '/about',
    consoleVersion: pkg.version || '3.5.0',
    nodeVersion: getNodeVersion(),
    arbiterUptime: formatUptime(getArbiterUptime()),
    modules: MODULES,
    totalModules: MODULES.length,
    adminUser: req.user,
    layout: 'layout'
  });
});

// POST /admin/about/deploy — Deploy Arbiter
router.post('/deploy', (req, res) => {
  const username = req.user?.username || 'unknown';
  console.log(`[DEPLOY] Deployment initiated by ${username} from About page`);
  exec(`nohup sudo /opt/scripts/deploy-arbiter.sh "${username}" > /tmp/deploy.log 2>&1 &`);
  res.json({
    success: true,
    message: 'Deploy started. Arbiter will restart momentarily.'
  });
});

// GET /admin/about/status — Health check
router.get('/status', (req, res) => {
  exec('systemctl is-active arbiter-3', (error, stdout) => {
    const isRunning = stdout.trim() === 'active';
    res.json({
      arbiter: isRunning ? 'running' : 'stopped',
      uptime: formatUptime(getArbiterUptime()),
      deployAvailable: fs.existsSync('/opt/scripts/deploy-arbiter.sh')
    });
  });
});

module.exports = router;
