// src/serialization/toFluent.ts
// Serialize Matrix component to Fluent DSL representation
//
// Fluent DSL is a TypeScript/JavaScript builder syntax for defining components.
//
// Reference: Vision/14-HOMOICONIC-ARCHITECTURE.md, Vision/20-COMPOSITION-DSL.md

import type { IComponentSchema } from './IComponentSchema';
import type { ISerializationOptions } from './ISerializationOptions';

/**
 * Convert component schema to Fluent DSL representation
 *
 * @example
 * toFluent({ name: 'Button', accepts: { click: { params: { id: { type: 'string' } } } }, emits: { clicked: {} } })
 * // Returns:
 * // component('Button')
 * //   .accepts('click', { id: 'string' })
 * //   .emits('clicked')
 */
export function toFluent(
  schema: IComponentSchema,
  options: ISerializationOptions = {}
): string {
  const { pretty = true, includeComments = false, indent = '  ' } = options;
  const lines: string[] = [];

  // Component declaration
  const mountArg = schema.mount ? `, { mount: '${schema.mount}' }` : '';
  lines.push(`component('${schema.name}'${mountArg})`);

  // Accepts (methods)
  for (const [name, method] of Object.entries(schema.accepts)) {
    if (includeComments && method.description) {
      lines.push(`${indent}// ${method.description}`);
    }

    const paramsStr = formatParams(method.params);
    if (paramsStr) {
      lines.push(`${indent}.accepts('${name}', ${paramsStr})`);
    } else {
      lines.push(`${indent}.accepts('${name}')`);
    }
  }

  // Emits (events)
  for (const [name, event] of Object.entries(schema.emits)) {
    if (includeComments && event.description) {
      lines.push(`${indent}// ${event.description}`);
    }

    const payloadStr = formatParams(event.payload);
    if (payloadStr) {
      lines.push(`${indent}.emits('${name}', ${payloadStr})`);
    } else {
      lines.push(`${indent}.emits('${name}')`);
    }
  }

  // Children
  if (schema.children && schema.children.length > 0) {
    for (const child of schema.children) {
      const childFluent = toFluent(child, { ...options, pretty: false });
      lines.push(`${indent}.child(${childFluent})`);
    }
  }

  // Build call
  lines.push(`${indent}.build()`);

  return pretty ? lines.join('\n') : lines.join('');
}

/**
 * Format parameters object as string
 */
function formatParams(params: Record<string, { type: string; optional?: boolean }> | undefined): string {
  if (!params || Object.keys(params).length === 0) {
    return '';
  }

  const entries = Object.entries(params).map(([name, schema]) => {
    const type = schema.optional ? `'${schema.type}?'` : `'${schema.type}'`;
    return `${name}: ${type}`;
  });

  return `{ ${entries.join(', ')} }`;
}
