/**
 * Smoke tests: Llm resource CRUD + apiKeyRef linkage against live mcpd.
 *
 * Exercises the Phase 1 CLI contract end-to-end:
 *   1. Create a secret carrying a fake API key.
 *   2. `mcpctl create llm` referencing that secret via --api-key-ref.
 *   3. `mcpctl describe llm` shows type/model/tier + the secret ref.
 *   4. `mcpctl get llms -o yaml` round-trips cleanly into `apply -f`.
 *   5. Delete llm + secret.
 *
 * Inference itself is covered in llm-infer.smoke.test.ts — this file is
 * purely about the registry.
 */
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import http from 'node:http';
import https from 'node:https';
import { execSync } from 'node:child_process';
import { writeFileSync, unlinkSync, mkdtempSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';

const MCPD_URL = process.env.MCPD_URL ?? 'https://mcpctl.ad.itaz.eu';
const SUFFIX = Date.now().toString(36);
const SECRET_NAME = `smoke-llm-sec-${SUFFIX}`;
const LLM_NAME = `smoke-llm-${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); });
  });
}

let mcpdUp = false;

describe('llm smoke', () => {
  beforeAll(async () => {
    mcpdUp = await healthz(MCPD_URL);
    if (!mcpdUp) {
      // eslint-disable-next-line no-console
      console.warn(`\n  ○ llm smoke: skipped — ${MCPD_URL}/healthz unreachable. Set MCPD_URL to override.\n`);
    }
  }, 20_000);

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

  it('creates a secret to hold the fake API key', () => {
    if (!mcpdUp) return;
    run(`delete secret ${SECRET_NAME}`); // idempotent cleanup
    const result = run(`create secret ${SECRET_NAME} --data token=sk-fake-xyz`);
    expect(result.code, result.stderr).toBe(0);
  });

  it('creates an Llm pointing at the secret via --api-key-ref', () => {
    if (!mcpdUp) return;
    run(`delete llm ${LLM_NAME}`);
    const cmd = [
      `create llm ${LLM_NAME}`,
      '--type openai',
      '--model gpt-4o-mini',
      '--tier fast',
      '--url http://nowhere.example:9000',
      `--api-key-ref ${SECRET_NAME}/token`,
      '--description smoke-test',
    ].join(' ');
    const result = run(cmd);
    expect(result.code, result.stderr || result.stdout).toBe(0);
    expect(result.stdout).toMatch(new RegExp(`llm '${LLM_NAME}'`));
  });

  it('describe llm shows the secret ref in sectioned output', () => {
    if (!mcpdUp) return;
    const result = run(`describe llm ${LLM_NAME}`);
    expect(result.code, result.stderr).toBe(0);
    expect(result.stdout).toContain(`=== LLM: ${LLM_NAME} ===`);
    expect(result.stdout).toContain('Type:');
    expect(result.stdout).toContain('openai');
    expect(result.stdout).toContain('Model:');
    expect(result.stdout).toContain('gpt-4o-mini');
    expect(result.stdout).toContain('API Key:');
    expect(result.stdout).toContain(SECRET_NAME);
    expect(result.stdout).toContain('token');
    // Raw key value must NOT appear — only the ref
    expect(result.stdout).not.toContain('sk-fake-xyz');
  });

  it('get llms shows the row with KEY column rendered as "secret://name/key"', () => {
    if (!mcpdUp) return;
    // Table output truncates the KEY column (≈34 chars), so the full
    // "secret://<name>/<key>" string won't appear verbatim in the row. Assert
    // against JSON output where the apiKeyRef round-trips as a structured
    // object.
    const result = run('get llms -o json');
    expect(result.code).toBe(0);
    const rows = JSON.parse(result.stdout) as Array<{ name: string; apiKeyRef?: { name: string; key: string } }>;
    const row = rows.find((r) => r.name === LLM_NAME);
    expect(row, `row ${LLM_NAME} must be present`).toBeDefined();
    expect(row!.apiKeyRef).toEqual({ name: SECRET_NAME, key: 'token' });
  });

  it('round-trips yaml output → apply -f', () => {
    if (!mcpdUp) return;
    const yaml = run(`get llm ${LLM_NAME} -o yaml`);
    expect(yaml.code).toBe(0);
    expect(yaml.stdout).toMatch(/kind:\s+llm/);
    expect(yaml.stdout).toContain(`name: ${LLM_NAME}`);
    expect(yaml.stdout).toContain(`name: ${SECRET_NAME}`); // apiKeyRef block

    // Change the description via apply -f with the YAML we just pulled.
    const dir = mkdtempSync(join(tmpdir(), 'mcpctl-smoke-'));
    const path = join(dir, 'llm.yaml');
    const amended = yaml.stdout.replace('description: smoke-test', 'description: smoke-test-amended');
    writeFileSync(path, amended);
    try {
      const applied = run(`apply -f ${path}`);
      expect(applied.code, applied.stderr || applied.stdout).toBe(0);
      const described = run(`describe llm ${LLM_NAME}`);
      expect(described.stdout).toContain('smoke-test-amended');
    } finally {
      unlinkSync(path);
    }
  });

  it('deletes the llm and leaves the underlying secret intact', () => {
    if (!mcpdUp) return;
    const del = run(`delete llm ${LLM_NAME}`);
    expect(del.code, del.stderr).toBe(0);

    // Secret still exists (apiKeyRef uses onDelete: SetNull so the secret isn't touched)
    const secret = run(`describe secret ${SECRET_NAME}`);
    expect(secret.code).toBe(0);
  });
});
