export interface MeshLabWebScript {
  version: 1;
  name: string;
  description?: string;
  createdAt: string;
  filters: { id: string; params: Record<string, unknown> }[];
}

export interface FilterRecord {
  id: string;
  name: string;
  params: Record<string, unknown>;
  timestamp: number;
}

export function historyToScript(history: FilterRecord[], name: string): MeshLabWebScript {
  return {
    version: 1,
    name,
    createdAt: new Date().toISOString(),
    filters: history.map((h) => ({ id: h.id, params: h.params })),
  };
}

export function generateShareUrl(script: MeshLabWebScript): string {
  const json = JSON.stringify(script);
  const encoded = btoa(unescape(encodeURIComponent(json)));
  const loc = typeof window !== 'undefined' ? window.location : { origin: '', pathname: '/' };
  const url = `${loc.origin}${loc.pathname}?script=${encoded}`;
  if (url.length > 2000) throw new Error('Script too long for URL sharing');
  return url;
}

export function loadScriptFromUrl(): MeshLabWebScript | null {
  const params = new URLSearchParams(window.location.search);
  const encoded = params.get('script');
  if (!encoded) return null;
  try {
    const json = decodeURIComponent(escape(atob(encoded)));
    return JSON.parse(json);
  } catch {
    return null;
  }
}
