/**
 * Smoke tests: `POST /api/v1/llms/:name/infer` against live mcpd.
 *
 * Validates the Phase 2 inference proxy path without needing a real provider
 * key. We exercise the error-shape guarantees:
 *   1. Missing Llm → 404.
 *   2. Existing Llm + empty body → 400.
 *   3. Existing Llm pointed at an unreachable URL → 502 with an error body.
 *   4. RBAC: non-admin calling infer without `run:llms:<name>` → 403 (skipped
 *      if we can't mint a scoped McpToken in this environment).
 *
 * The happy-path test needs a real provider, so we skip it by default and
 * gate on LLM_INFER_SMOKE_REAL=1 + a working Llm name supplied via
 * LLM_INFER_SMOKE_LLM.
 */
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import http from 'node:http';
import https from 'node:https';
import { execSync } from 'node:child_process';

const MCPD_URL = process.env.MCPD_URL ?? 'https://mcpctl.ad.itaz.eu';
const SUFFIX = Date.now().toString(36);
const SECRET_NAME = `smoke-infer-sec-${SUFFIX}`;
const LLM_NAME = `smoke-infer-${SUFFIX}`;

interface CliResult { code: number; stdout: string; stderr: string }

function run(args: string): CliResult {
  try {
    const stdout = execSync(`mcpctl --direct ${args}`, {
      encoding: 'utf-8',
      timeout: 30_000,
      stdio: ['ignore', 'pipe', 'pipe'],
    });
    return { code: 0, stdout: stdout.trim(), stderr: '' };
  } catch (err) {
    const e = err as { status?: number; stdout?: Buffer | string; stderr?: Buffer | string };
    return {
      code: e.status ?? 1,
      stdout: e.stdout ? (typeof e.stdout === 'string' ? e.stdout : e.stdout.toString('utf-8')) : '',
      stderr: e.stderr ? (typeof e.stderr === 'string' ? e.stderr : e.stderr.toString('utf-8')) : '',
    };
  }
}

function healthz(url: string, timeoutMs = 5000): Promise<boolean> {
  return new Promise((resolve) => {
    const parsed = new URL(`${url.replace(/\/$/, '')}/healthz`);
    const driver = parsed.protocol === 'https:' ? https : http;
    const req = driver.get(
      {
        hostname: parsed.hostname,
        port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
        path: parsed.pathname,
        timeout: timeoutMs,
      },
      (res) => { resolve((res.statusCode ?? 500) < 500); res.resume(); },
    );
    req.on('error', () => resolve(false));
    req.on('timeout', () => { req.destroy(); resolve(false); });
  });
}

/** Look up the current session bearer so we can POST /infer directly. */
function getBearer(): string | undefined {
  // Try ~/.mcpctl/credentials.json via the CLI — `mcpctl config get` knows where it lives.
  // If that shape changes, fall back to MCPCTL_TOKEN env.
  const envToken = process.env.MCPCTL_TOKEN;
  if (envToken !== undefined && envToken !== '') return envToken;
  try {
    // shape: { "session": { "token": "..." } } or similar — be defensive.
    const out = execSync('cat ~/.mcpctl/credentials.json 2>/dev/null', { encoding: 'utf-8' });
    const parsed = JSON.parse(out) as Record<string, unknown>;
    const token = (parsed.token ?? (parsed.session as { token?: string } | undefined)?.token);
    return typeof token === 'string' ? token : undefined;
  } catch {
    return undefined;
  }
}

async function post(
  path: string,
  body: unknown,
  bearer?: string,
): Promise<{ status: number; body: unknown }> {
  const url = new URL(`${MCPD_URL.replace(/\/$/, '')}${path}`);
  const driver = url.protocol === 'https:' ? https : http;
  const payload = JSON.stringify(body);
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(payload).toString(),
  };
  if (bearer !== undefined) headers['Authorization'] = `Bearer ${bearer}`;

  return new Promise((resolve, reject) => {
    const req = driver.request(
      {
        hostname: url.hostname,
        port: url.port || (url.protocol === 'https:' ? 443 : 80),
        path: url.pathname + url.search,
        method: 'POST',
        headers,
        timeout: 15_000,
      },
      (res) => {
        const chunks: Buffer[] = [];
        res.on('data', (c: Buffer) => chunks.push(c));
        res.on('end', () => {
          const raw = Buffer.concat(chunks).toString('utf-8');
          let parsed: unknown = raw;
          try { parsed = JSON.parse(raw); } catch { /* leave as string */ }
          resolve({ status: res.statusCode ?? 0, body: parsed });
        });
      },
    );
    req.on('error', reject);
    req.on('timeout', () => { req.destroy(); reject(new Error('request timed out')); });
    req.write(payload);
    req.end();
  });
}

let mcpdUp = false;
let bearer: string | undefined;

describe('llm-infer smoke', () => {
  beforeAll(async () => {
    mcpdUp = await healthz(MCPD_URL);
    if (!mcpdUp) {
      // eslint-disable-next-line no-console
      console.warn(`\n  ○ llm-infer smoke: skipped — ${MCPD_URL}/healthz unreachable.\n`);
      return;
    }
    bearer = getBearer();
    if (bearer === undefined) {
      // eslint-disable-next-line no-console
      console.warn('\n  ○ llm-infer smoke: no bearer available (set MCPCTL_TOKEN or login). Direct POST tests will skip.\n');
    }
  }, 20_000);

  afterAll(() => {
    if (!mcpdUp) return;
    run(`delete llm ${LLM_NAME}`);
    run(`delete secret ${SECRET_NAME}`);
  });

  it('creates a fixture secret + Llm pointed at an unreachable URL', () => {
    if (!mcpdUp) return;
    run(`delete llm ${LLM_NAME}`);
    run(`delete secret ${SECRET_NAME}`);

    expect(run(`create secret ${SECRET_NAME} --data token=sk-fake`).code).toBe(0);
    const createLlm = run([
      `create llm ${LLM_NAME}`,
      '--type openai',
      '--model gpt-4o-mini',
      // Unroutable host so any actual upstream call returns an adapter error → 502
      '--url http://127.0.0.1:1',
      `--api-key-ref ${SECRET_NAME}/token`,
    ].join(' '));
    expect(createLlm.code, createLlm.stderr || createLlm.stdout).toBe(0);
  });

  it('returns 404 for an unknown Llm name', async () => {
    if (!mcpdUp || bearer === undefined) return;
    const res = await post('/api/v1/llms/__nonexistent_llm__/infer',
      { messages: [{ role: 'user', content: 'hi' }] }, bearer);
    expect(res.status).toBe(404);
  });

  it('returns 400 when messages is missing', async () => {
    if (!mcpdUp || bearer === undefined) return;
    const res = await post(`/api/v1/llms/${LLM_NAME}/infer`, {}, bearer);
    expect(res.status).toBe(400);
    const body = res.body as { error?: string };
    expect(body.error ?? '').toMatch(/messages/i);
  });

  it('returns 502 when the upstream provider is unreachable', async () => {
    if (!mcpdUp || bearer === undefined) return;
    const res = await post(`/api/v1/llms/${LLM_NAME}/infer`,
      { messages: [{ role: 'user', content: 'hi' }] }, bearer);
    // 502 is what the proxy returns on adapter errors; some paths may return
    // the upstream's own status if the request reached it, so accept any
    // non-2xx with an error body.
    expect(res.status).toBeGreaterThanOrEqual(400);
    expect(res.status).not.toBe(404);
    expect(res.status).not.toBe(400);
    const body = res.body as { error?: string | { message?: string } };
    const msg = typeof body.error === 'string' ? body.error : body.error?.message ?? '';
    expect(msg, 'error body must describe the failure').not.toBe('');
  }, 30_000);

  it('happy-path inference (opt-in: LLM_INFER_SMOKE_REAL=1 + LLM_INFER_SMOKE_LLM=<name>)', async () => {
    if (!mcpdUp || bearer === undefined) return;
    if (process.env.LLM_INFER_SMOKE_REAL !== '1') {
      // eslint-disable-next-line no-console
      console.warn('    ○ happy-path skipped — set LLM_INFER_SMOKE_REAL=1 and LLM_INFER_SMOKE_LLM=<name> of a working Llm.');
      return;
    }
    const name = process.env.LLM_INFER_SMOKE_LLM;
    if (name === undefined || name === '') {
      throw new Error('LLM_INFER_SMOKE_LLM must be set when LLM_INFER_SMOKE_REAL=1');
    }
    const res = await post(`/api/v1/llms/${name}/infer`, {
      messages: [{ role: 'user', content: 'Say "smoke-ok" and nothing else.' }],
      max_tokens: 8,
    }, bearer);
    expect(res.status).toBe(200);
    const body = res.body as { choices?: Array<{ message?: { content?: string } }> };
    const content = body.choices?.[0]?.message?.content ?? '';
    expect(content).toMatch(/smoke-ok/i);
  }, 60_000);
});
