import { defineStore } from 'pinia';
import { calibrationApi } from '@/api/calibration';
import type {
  CalibrationFile,
  DocumentMetadata,
  DocumentChunk,
  KnowledgeRelation,
  Highlight,
} from '@/types/calibration';

interface CalibrationState {
  files: CalibrationFile[];
  selectedFileId: string | null;
  currentMetadata: DocumentMetadata | null;
  currentChunks: DocumentChunk[];
  currentRelations: KnowledgeRelation[];
  highlights: Highlight[];
  filterType: string;
  isLoading: boolean;
  isDirty: boolean;
  lastParsedTime: string | null;
}

export const useCalibrationStore = defineStore('calibration', {
  state: (): CalibrationState => ({
    files: [],
    selectedFileId: null,
    currentMetadata: null,
    currentChunks: [],
    currentRelations: [],
    highlights: [],
    filterType: 'all',
    isLoading: false,
    isDirty: false,
    lastParsedTime: null,
  }),

  getters: {
    selectedFile: (state): CalibrationFile | undefined =>
      state.files.find((f) => f.id === state.selectedFileId),

    filteredFiles: (state): CalibrationFile[] => {
      if (state.filterType === 'all') return state.files;
      return state.files.filter((f) => f.type === state.filterType);
    },

    pendingCount: (state): number => state.files.filter((f) => f.status === 'pending').length,
  },

  actions: {
    async fetchFiles(filter?: string) {
      this.isLoading = true;
      try {
        const response = await calibrationApi.getFiles({ type: filter });
        this.files = response.data;
      } catch (error) {
        console.error('Failed to fetch files:', error);
      } finally {
        this.isLoading = false;
      }
    },

    async selectFile(fileId: string) {
      this.selectedFileId = fileId;
      this.isLoading = true;
      try {
        const [metadata, chunks, relations] = await Promise.all([
          calibrationApi.getMetadata(fileId),
          calibrationApi.getChunks(fileId),
          calibrationApi.getRelations(fileId),
        ]);
        this.currentMetadata = metadata.data;
        this.currentChunks = chunks.data;
        this.currentRelations = relations.data;
        this.lastParsedTime = metadata.data.lastParsed || null;
        this.isDirty = false;
      } catch (error) {
        console.error('Failed to load file details:', error);
      } finally {
        this.isLoading = false;
      }
    },

    async saveDraft() {
      if (!this.selectedFileId || !this.currentMetadata) return;
      try {
        await calibrationApi.updateMetadata(this.selectedFileId, this.currentMetadata);
        this.isDirty = false;
      } catch (error) {
        console.error('Failed to save draft:', error);
        throw error;
      }
    },

    async publish() {
      if (!this.selectedFileId) return;
      try {
        await calibrationApi.publishFile(this.selectedFileId);
        await this.fetchFiles();
      } catch (error) {
        console.error('Failed to publish file:', error);
        throw error;
      }
    },

    setFilterType(type: string) {
      this.filterType = type;
    },

    updateMetadata(metadata: Partial<DocumentMetadata>) {
      if (this.currentMetadata) {
        this.currentMetadata = { ...this.currentMetadata, ...metadata };
        this.isDirty = true;
      }
    },

    setHighlights(highlights: Highlight[]) {
      this.highlights = highlights;
    },
  },
});
