/**
 * Build a "Reference Format" block for the chat system prompt that lists
 * each installed connector's URL pattern and asks the LLM to emit
 * markdown links directly when mentioning IDs.
 *
 * Output goes into buildSystemPrompt in agent-loop.ts. Base URLs are read
 * from connector-configs.json so the prompt only mentions connectors the
 * user has actually configured — no broken/placeholder URLs leak.
 */

import { getInstalledConnector } from '../connectors/registry';

interface RefLine {
  /** Human reference type for the prompt. */
  label: string;
  /** Example template the LLM should follow. */
  example: string;
}

/**
 * Returns a markdown-friendly multiline string section, or empty string
 * if no connector is configured for any of the rules. Caller appends it
 * verbatim to the system prompt.
 */
export function buildReferencePromptSection(): string {
  const out: RefLine[] = [];

  // Helper — read base_url from a connector, trailing slash stripped.
  const baseOf = (id: string): string | null => {
    const cfg = getInstalledConnector(id)?.config as { base_url?: string } | undefined;
    const v = (cfg?.base_url || '').trim().replace(/\/+$/, '');
    return v || null;
  };

  const mantis = baseOf('mantis');
  if (mantis) {
    out.push({
      label: 'Mantis bug',
      example: `[Mantis #1226625](${mantis}/bug_view_page.php?bug_id=1226625)`,
    });
  }

  const gitlab = baseOf('gitlab');
  if (gitlab) {
    out.push({
      label: 'GitLab merge request',
      example: `[MR !14860](${gitlab}/-/merge_requests/14860)`,
    });
    out.push({
      label: 'GitLab issue',
      example: `[Issue #789](${gitlab}/-/issues/789)`,
    });
  }

  const blackduck = baseOf('blackduck');
  if (blackduck) {
    out.push({
      label: 'Black Duck advisory',
      example: `[BDSA-2024-0001](${blackduck}/api/vulnerabilities/BDSA-2024-0001)`,
    });
  }

  // Always include — self-contained, doesn't need a connector
  out.push({
    label: 'CVE',
    example: '[CVE-2024-1234](https://nvd.nist.gov/vuln/detail/CVE-2024-1234)',
  });

  if (out.length === 0) return '';

  const lines = [
    'Reference format — when mentioning these IDs in your reply, emit them as inline markdown links (substitute the real id):',
  ];
  for (const r of out) {
    lines.push(`- ${r.label}: ${r.example}`);
  }
  lines.push(
    'Always use the URLs shown above; do NOT invent hostnames. If a category is not listed, just mention the id as plain text — the UI will auto-link known patterns as a fallback.',
  );
  return lines.join('\n');
}
