import type { LogicNode } from './strategyTypes';
import type { EdgeHandleBinding } from './strategyFlowLayout';
import { defaultStartMeta, type StartCombineOp, type StartNodeMeta } from './strategyStartNodes';

export type SignalFlowLayoutSnapshot = {
  positions: Record<string, { x: number; y: number }>;
  edgeHandles: Record<string, EdgeHandleBinding>;
  orphans?: LogicNode[];
  /** START 노드별 조건 판별 시간봉 */
  startMeta?: Record<string, StartNodeMeta>;
  /** 기본 START 외 추가 START 노드 ID (순서 유지) */
  extraStartIds?: string[];
  /** 추가 START에 연결된 서브트리 루트 */
  extraRoots?: Record<string, LogicNode | null>;
  /** START 2개 이상일 때 분기 결합 (AND | OR) */
  startCombineOp?: StartCombineOp;
};

export type FlowLayoutChangePayload = Omit<SignalFlowLayoutSnapshot, 'orphans'> & {
  tab: 'buy' | 'sell';
};

export type StrategyFlowLayoutStore = {
  buy: SignalFlowLayoutSnapshot;
  sell: SignalFlowLayoutSnapshot;
};

const STORAGE_KEY = 'gc_se_flow_layout_v1';

export function emptySignalFlowLayout(): SignalFlowLayoutSnapshot {
  return {
    positions: {},
    edgeHandles: {},
    orphans: [],
    startMeta: defaultStartMeta(),
    extraStartIds: [],
    extraRoots: {},
  };
}

export function emptyStrategyFlowLayout(): StrategyFlowLayoutStore {
  return { buy: emptySignalFlowLayout(), sell: emptySignalFlowLayout() };
}

export function loadStrategyFlowLayout(strategyKey: string): StrategyFlowLayoutStore | null {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return null;
    const all = JSON.parse(raw) as Record<string, StrategyFlowLayoutStore>;
    return all[strategyKey] ?? null;
  } catch {
    return null;
  }
}

export function saveStrategyFlowLayout(strategyKey: string, layout: StrategyFlowLayoutStore): void {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    const all: Record<string, StrategyFlowLayoutStore> = raw ? JSON.parse(raw) : {};
    all[strategyKey] = layout;
    localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  } catch {
    /* ignore quota / private mode */
  }
}

export function deleteStrategyFlowLayout(strategyKey: string): void {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return;
    const all = JSON.parse(raw) as Record<string, StrategyFlowLayoutStore>;
    delete all[strategyKey];
    localStorage.setItem(STORAGE_KEY, JSON.stringify(all));
  } catch {
    /* ignore */
  }
}

export function migrateStrategyFlowLayout(fromKey: string, toKey: string): void {
  if (fromKey === toKey) return;
  const layout = loadStrategyFlowLayout(fromKey);
  if (!layout) return;
  saveStrategyFlowLayout(toKey, layout);
  deleteStrategyFlowLayout(fromKey);
}
