/**
 * README.md Generator
 *
 * Auto-generates a human-readable README for a symbol folder.
 */

/**
 * Generate README.md content.
 *
 * @param {object} input
 * @param {string} input.symbolName
 * @param {string} input.manufacturer
 * @param {string} input.package
 * @param {string} input.description
 * @param {string} input.datasheetUrl
 * @param {Array<{name: string, number: string, type: string, group?: string, description: string}>} input.pins
 * @param {Array<{name: string, description: string}>} [input.groups]
 * @param {string} [input.viewerUrl] - Full URL to the viewer HTML in the Adom app
 * @returns {string} Markdown content
 */
export function generateReadme(input) {
  const { symbolName, manufacturer, package: pkg, description, datasheetUrl, pins, groups, viewerUrl } = input;

  const lines = [];

  lines.push(`# ${symbolName}`);
  lines.push('');
  if (description) lines.push(`${description}`);
  lines.push('');

  // Part info table
  lines.push('| Field | Value |');
  lines.push('|-------|-------|');
  if (manufacturer) lines.push(`| Manufacturer | ${manufacturer} |`);
  if (pkg) lines.push(`| Package | ${pkg} |`);
  lines.push(`| Pins | ${pins.length} |`);
  if (datasheetUrl) lines.push(`| Datasheet | [PDF](${datasheetUrl}) |`);
  if (viewerUrl) lines.push(`| Viewer | [Interactive](${viewerUrl}) |`);
  lines.push('');

  // Pin table
  lines.push('## Pin Table');
  lines.push('');
  lines.push('| # | Name | Type | Group | Description |');
  lines.push('|---|------|------|-------|-------------|');
  for (const pin of pins) {
    const group = pin.group || '';
    const desc = (pin.description || '').replace(/\|/g, '\\|').replace(/\n/g, ' ');
    const truncDesc = desc.length > 120 ? desc.slice(0, 117) + '...' : desc;
    lines.push(`| ${pin.number} | ${pin.name} | ${pin.type} | ${group} | ${truncDesc} |`);
  }
  lines.push('');

  // Group descriptions
  if (groups && groups.length > 0) {
    lines.push('## Pin Groups');
    lines.push('');
    for (const group of groups) {
      lines.push(`### ${group.name}`);
      lines.push('');
      if (group.description) lines.push(group.description);
      lines.push('');
    }
  }

  lines.push('---');
  lines.push('');
  lines.push('*Generated by Adom Symbol Creator Service*');
  lines.push('');

  return lines.join('\n');
}