import os from 'os';
import type { Tool, ToolResult } from '../types.js';

function formatUptime(seconds: number): string {
  const days = Math.floor(seconds / 86400);
  const hours = Math.floor((seconds % 86400) / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  return `${days}d ${hours}h ${minutes}m`;
}

function formatBytes(bytes: number): string {
  return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
}

export const systemInfoTool: Tool = {
  name: 'system.info',
  description: 'Get current system information including date, time, hostname, OS, platform, architecture, uptime, Node.js version, and memory usage.',
  inputSchema: {
    type: 'object',
    properties: {},
    required: [],
  },
  execute: async (_rawArgs: unknown): Promise<ToolResult> => {
    try {
      const now = new Date();
      const dateStr = now.toLocaleDateString('en-US', {
        weekday: 'long',
        year: 'numeric',
        month: 'long',
        day: 'numeric',
      });
      const timeStr = now.toLocaleTimeString('en-US', {
        hour: '2-digit',
        minute: '2-digit',
        timeZoneName: 'short',
        hour12: false,
      });
      const isoStr = now.toISOString();

      const totalMem = os.totalmem();
      const freeMem = os.freemem();

      const lines = [
        `Date:          ${dateStr}`,
        `Time:          ${timeStr}`,
        `ISO 8601:      ${isoStr}`,
        `Hostname:      ${os.hostname()}`,
        `Platform:      ${os.platform()}`,
        `Architecture:  ${os.arch()}`,
        `OS Release:    ${os.release()}`,
        `Uptime:        ${formatUptime(os.uptime())}`,
        `Node.js:       ${process.version}`,
        `Memory Total:  ${formatBytes(totalMem)}`,
        `Memory Free:   ${formatBytes(freeMem)}`,
        `Working Dir:   ${process.cwd()}`,
      ];

      return { success: true, output: lines.join('\n') };
    } catch (error) {
      return { success: false, output: '', error: error instanceof Error ? error.message : String(error) };
    }
  },
};
