import { AnnotationData, Highlight, Comment, Rect } from '../types/pdfReader';

export const createAnnotationData = (): AnnotationData => ({
  highlights: [],
  comments: [],
  version: '2.0.0',
  createdAt: Date.now()
});

export const generateId = (): string => {
  return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
};

const migrateHighlight = (highlight: any): Highlight => {
  if ('positions' in highlight) {
    return highlight as Highlight;
  }
  if ('position' in highlight) {
    return {
      ...highlight,
      positions: [highlight.position as Rect]
    };
  }
  return highlight;
};

export const addHighlight = (
  data: AnnotationData,
  highlight: Omit<Highlight, 'id'>
): AnnotationData => {
  const newHighlight: Highlight = {
    ...highlight,
    id: generateId()
  };

  return {
    ...data,
    highlights: [...data.highlights, newHighlight]
  };
};

export const removeHighlight = (
  data: AnnotationData,
  highlightId: string
): AnnotationData => {
  return {
    ...data,
    highlights: data.highlights.filter(h => h.id !== highlightId),
    comments: data.comments.filter(c => c.highlightId !== highlightId)
  };
};

export const addComment = (
  data: AnnotationData,
  highlightId: string,
  text: string
): AnnotationData => {
  const newComment: Comment = {
    id: generateId(),
    highlightId,
    text,
    createdAt: Date.now()
  };

  return {
    ...data,
    comments: [...data.comments, newComment]
  };
};

export const removeComment = (
  data: AnnotationData,
  commentId: string
): AnnotationData => {
  return {
    ...data,
    comments: data.comments.filter(c => c.id !== commentId)
  };
};

export const exportAnnotations = (data: AnnotationData): void => {
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `annotations-${new Date().toISOString().slice(0, 10)}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

export const importAnnotations = (file: File): Promise<AnnotationData> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const data = JSON.parse(e.target?.result as string);
        const migratedData: AnnotationData = {
          ...data,
          highlights: data.highlights.map(migrateHighlight),
          version: '2.0.0'
        };
        resolve(migratedData);
      } catch (err) {
        reject(err);
      }
    };
    reader.onerror = reject;
    reader.readAsText(file);
  });
};
