import { describe, it, expect } from 'vitest';
import { systemInfoTool } from './system-info.js';

describe('system.info tool', () => {
  // ── Metadata ─────────────────────────────────────────────────────────────

  it('has correct metadata', () => {
    expect(systemInfoTool.name).toBe('system.info');
    expect(systemInfoTool.description).toBeTruthy();
    expect(systemInfoTool.inputSchema.type).toBe('object');
  });

  // ── Execution ────────────────────────────────────────────────────────────

  it('returns success with system info', async () => {
    const result = await systemInfoTool.execute({});

    expect(result.success).toBe(true);
    expect(typeof result.output).toBe('string');
    expect(result.output!.length).toBeGreaterThan(0);
  });

  it('output contains expected fields', async () => {
    const result = await systemInfoTool.execute({});

    expect(result.success).toBe(true);
    const output = result.output!;

    const expectedFields = [
      'Date:',
      'Time:',
      'Hostname:',
      'Platform:',
      'Architecture:',
      'Node.js:',
      'Uptime:',
      'Memory Total:',
    ];

    for (const field of expectedFields) {
      expect(output).toContain(field);
    }
  });

  it('output contains valid ISO timestamp', async () => {
    const result = await systemInfoTool.execute({});

    expect(result.success).toBe(true);
    const output = result.output!;

    // Find the line containing 'ISO 8601:'
    const isoLine = output.split('\n').find((line) => line.includes('ISO 8601:'));
    expect(isoLine).toBeTruthy();

    // Extract the ISO string and validate it
    const isoMatch = isoLine!.match(/ISO 8601:\s*(.+)/);
    expect(isoMatch).toBeTruthy();

    const isoString = isoMatch![1].trim();
    const parsed = new Date(isoString);
    expect(parsed.toISOString()).toBe(isoString);
  });

  it('output contains working directory', async () => {
    const result = await systemInfoTool.execute({});

    expect(result.success).toBe(true);
    expect(result.output).toContain('Working Dir:');
  });

  // ── Idempotency ──────────────────────────────────────────────────────────

  it('handles repeated calls', async () => {
    const result1 = await systemInfoTool.execute({});
    const result2 = await systemInfoTool.execute({});

    expect(result1.success).toBe(true);
    expect(result2.success).toBe(true);
    expect(typeof result1.output).toBe('string');
    expect(typeof result2.output).toBe('string');
    expect(result1.output!.length).toBeGreaterThan(0);
    expect(result2.output!.length).toBeGreaterThan(0);
  });
});
