/**
 * Smoke tests: vllm-managed provider lifecycle.
 *
 * These tests require a running mcplocal instance.
 * Run with: pnpm test:smoke
 *
 * Tests verify:
 *   - mcpctl status shows vllm-managed provider state
 *   - Provider details endpoint includes managed state
 *
 * If no vllm-managed provider is configured, tests skip gracefully.
 */
import { describe, it, expect, beforeAll } from 'vitest';
import { isMcplocalRunning, getMcplocalUrl, mcpctl } from './mcp-client.js';
import http from 'node:http';

interface ProvidersResponse {
  providers: string[];
  tiers: { fast: string[]; heavy: string[] };
  health: Record<string, boolean>;
  details?: Record<string, { managed: boolean; state?: string; lastError?: string }>;
}

function fetchProviders(): Promise<ProvidersResponse | null> {
  return new Promise((resolve) => {
    const url = getMcplocalUrl();
    const req = http.get(`${url}/llm/providers`, { timeout: 5000 }, (res) => {
      const chunks: Buffer[] = [];
      res.on('data', (chunk: Buffer) => chunks.push(chunk));
      res.on('end', () => {
        try {
          resolve(JSON.parse(Buffer.concat(chunks).toString('utf-8')) as ProvidersResponse);
        } catch {
          resolve(null);
        }
      });
    });
    req.on('error', () => resolve(null));
    req.on('timeout', () => { req.destroy(); resolve(null); });
  });
}

describe('Smoke: vllm-managed provider', () => {
  let available = false;
  let hasManagedProvider = false;

  beforeAll(async () => {
    console.log('');
    console.log('  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
    console.log('  Smoke Test: vllm-managed provider');
    console.log('  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');

    available = await isMcplocalRunning();
    if (!available) {
      console.log('\n  ✗ mcplocal not running — all tests will be skipped\n');
      return;
    }

    // Check if a vllm-managed provider is configured
    const providers = await fetchProviders();
    if (providers?.details) {
      hasManagedProvider = Object.values(providers.details).some((d) => d.managed);
    }

    if (!hasManagedProvider) {
      console.log('\n  ○ No vllm-managed provider configured — lifecycle tests will be skipped');
      console.log('    Configure with: mcpctl config setup → Advanced → Fast → "Run vLLM Instance"\n');
    }
  });

  it('mcpctl status runs without error', async () => {
    if (!available) return;
    const output = await mcpctl('status');
    expect(output).toContain('mcpctl v');
    expect(output).toContain('mcplocal:');
  });

  it('/llm/providers returns valid response', async () => {
    if (!available) return;
    const providers = await fetchProviders();
    expect(providers).not.toBeNull();
    expect(providers!.providers).toBeInstanceOf(Array);
    expect(providers!.tiers).toHaveProperty('fast');
    expect(providers!.tiers).toHaveProperty('heavy');
  });

  it('managed provider shows lifecycle state in details', async () => {
    if (!available || !hasManagedProvider) return;
    const providers = await fetchProviders();
    expect(providers?.details).toBeDefined();

    const managedEntries = Object.entries(providers!.details!).filter(([, d]) => d.managed);
    expect(managedEntries.length).toBeGreaterThan(0);

    for (const [name, detail] of managedEntries) {
      expect(detail.state).toBeDefined();
      expect(['stopped', 'starting', 'running', 'error']).toContain(detail.state);
      console.log(`    ${name}: ${detail.state}${detail.lastError ? ` (${detail.lastError})` : ''}`);
    }
  });

  it('mcpctl status shows managed provider state', async () => {
    if (!available || !hasManagedProvider) return;
    const output = await mcpctl('status');
    // Should show one of the managed states
    const hasState = output.includes('running')
      || output.includes('stopped')
      || output.includes('starting')
      || output.includes('error');
    expect(hasState).toBe(true);
  });
});
