import type { ScreenplayElement } from '../screenplay/types';
import type { ScreenplayExporter, ExportOptions, ExportResult } from './types';
import { CONTENT_TYPES, EXTENSIONS } from './types';

const LINE_TYPE_MAP: Record<string, string> = {
  sceneHeading: '[SCENE]',
  action: '[ACTION]',
  character: '[CHAR]',
  dialogue: '[DIALOG]',
  parenthetical: '[PAREN]',
  transition: '[TRANS]',
  note: '[NOTE]',
  retained: '[RETAINED]',
  centered: '[CENTER]',
};

export class ScreenplayProExporter implements ScreenplayExporter {
  public readonly supportedFormats: readonly ['screenplay-pro'] = ['screenplay-pro'];

  public export(elements: ScreenplayElement[], options: ExportOptions): ExportResult {
    const lines: string[] = [];

    lines.push('[HEADER]');
    lines.push('Version\t1.0');
    lines.push('Title\t' + (options.title || 'Untitled'));
    lines.push('Author\t' + (options.author || ''));
    if (options.contact) lines.push('Contact\t' + options.contact);
    lines.push('Date\t' + (options.datetime || new Date().toISOString().split('T')[0]));
    lines.push('Template\t' + (options.template || 'standard'));
    lines.push('');

    lines.push('[CONTENT]');

    for (const el of elements) {
      const marker = LINE_TYPE_MAP[el.type] || '[ACTION]';
      const content = el.content.trim();
      const page = el.page != null ? String(el.page) : '';
      const line = el.line != null ? String(el.line) : '';

      const tabSep = '\t';
      lines.push(marker + tabSep + content + tabSep + page + tabSep + line);
    }

    lines.push('');
    lines.push('[END]');

    const content = lines.join('\n');
    const filename = (options.title || 'screenplay').replace(/[^a-zA-Z0-9]/g, '_');

    return {
      format: 'screenplay-pro',
      contentType: CONTENT_TYPES['screenplay-pro'],
      extension: EXTENSIONS['screenplay-pro'],
      data: content,
      filename: filename + EXTENSIONS['screenplay-pro'],
    };
  }
}
