import type { PlacedSymbol, EpcWaypoint } from './types.js';
import { SYMBOLS } from './symbols.js';

/** Map of symbolId → current default {w, h} for migration */
const DEFAULT_SIZES = new Map(SYMBOLS.map(s => [s.id, { w: s.w, h: s.h }]));

/** Known outdated defaults: symbolId → [{oldW, oldH}] */
const OUTDATED_SIZES: Record<string, { w: number; h: number }[]> = {
  photoeye:   [{ w: 56, h: 20 }, { w: 30, h: 14 }],
  photoeye_v: [{ w: 56, h: 20 }, { w: 30, h: 14 }],
};

/** JSON shape stored in localStorage / exported JSON files */
export interface SerializedSymbol {
  symbolId: string;
  name: string;
  label?: string;
  file: string;
  x: number;
  y: number;
  w: number;
  h: number;
  w2?: number;
  rotation?: number;
  mirrored?: boolean;
  curveAngle?: number;
  epcWaypoints?: EpcWaypoint[];
  pdpCBs?: number[];
}

export function serializeSymbol(sym: PlacedSymbol): SerializedSymbol {
  return {
    symbolId: sym.symbolId,
    name: sym.name,
    label: sym.label || undefined,
    file: sym.file,
    x: sym.x,
    y: sym.y,
    w: sym.w,
    h: sym.h,
    w2: sym.w2,
    rotation: sym.rotation || undefined,
    mirrored: sym.mirrored || undefined,
    curveAngle: sym.curveAngle,
    epcWaypoints: sym.epcWaypoints,
    pdpCBs: sym.pdpCBs,
  };
}

export function deserializeSymbol(data: SerializedSymbol, id: number): PlacedSymbol {
  let { w, h } = data;

  // Migrate outdated default sizes to current defaults
  const outdated = OUTDATED_SIZES[data.symbolId];
  if (outdated) {
    const current = DEFAULT_SIZES.get(data.symbolId);
    if (current && outdated.some(o => o.w === w && o.h === h)) {
      w = current.w;
      h = current.h;
    }
  }

  return {
    id,
    symbolId: data.symbolId,
    name: data.name,
    label: data.label || '',
    file: data.file?.replace('_no_comm.svg', '.svg') || data.file,
    x: data.x,
    y: data.y,
    w,
    h,
    w2: data.w2,
    rotation: data.rotation || 0,
    mirrored: data.mirrored || false,
    curveAngle: data.curveAngle,
    epcWaypoints: data.epcWaypoints,
    pdpCBs: data.pdpCBs,
  };
}
