import type { CharacterDNA } from '../../types/character.js';
import { validateDNA } from './dna-schema.js';

/**
 * Serialize a CharacterDNA object to a JSON string.
 * Uses 2-space indentation for readability.
 */
export function serializeDNA(dna: CharacterDNA): string {
  return JSON.stringify(dna, null, 2);
}

/**
 * Parse a JSON string into a CharacterDNA object with validation.
 * Throws if the JSON is invalid or doesn't match the CharacterDNA schema.
 */
export function parseDNA(json: string): CharacterDNA {
  let parsed: unknown;
  try {
    parsed = JSON.parse(json);
  } catch {
    throw new Error('Invalid JSON: failed to parse input string');
  }

  const result = validateDNA(parsed);
  if (!result.valid) {
    throw new Error(`Invalid CharacterDNA: ${result.errors.join('; ')}`);
  }

  return parsed as CharacterDNA;
}

/**
 * Deep clone a CharacterDNA object via serialize/parse round-trip.
 * Guarantees a completely independent copy.
 */
export function cloneDNA(dna: CharacterDNA): CharacterDNA {
  return JSON.parse(JSON.stringify(dna)) as CharacterDNA;
}
