/*
*  author: Yagnik Poshiya
*  organization: Webbrains Technologies Private Limited
*/

import type { StorageDocumentItem } from '@/lib/storage/storage-types';

/**
 * Formats that can be edited in the browser.
 *
 * Only plain text. The other allowed upload formats are either binary or a
 * packaged archive (pdf, doc, docx, odt, pages), and rtf is text but its
 * control words are not something a person should hand-edit.
 */
export const EDITABLE_EXTENSIONS = ['txt', 'md', 'log'] as const;

/**
 * Above this, the editor refuses to open and the user is pointed at
 * download / edit locally / re-upload. A textarea holding megabytes of text
 * re-renders badly and the highlight overlay has to re-tokenise all of it.
 */
export const MAX_EDITABLE_BYTES = 1024 * 1024;

export const EDITABLE_EXTENSIONS_LABEL = '.txt, .md and .log';

export type StorageEditState = {
  editable: boolean;
  /** Why editing is unavailable. Null when it is available. */
  reason: string | null;
};

export function isEditableExtension(extension: string): boolean {
  const ext = String(extension ?? '').trim().toLowerCase().replace(/^\./, '');
  return (EDITABLE_EXTENSIONS as readonly string[]).includes(ext);
}

export function formatEditableSizeLimit(): string {
  return `${Math.round(MAX_EDITABLE_BYTES / 1024 / 1024)} MB`;
}

/**
 * Single source of truth for "can this document be edited right now".
 *
 * The menu item and the API both call this, so a disabled button and a
 * rejected request always agree on the reason.
 */
export function getStorageDocumentEditState(doc: {
  fileExtension: string;
  fileSizeBytes: number;
  status: string;
  hasActiveEmbeddingJob: boolean;
}): StorageEditState {
  if (!isEditableExtension(doc.fileExtension)) {
    return {
      editable: false,
      reason: `Only ${EDITABLE_EXTENSIONS_LABEL} files can be edited here.`,
    };
  }

  // Editing mid-embedding would race the worker: it reads the object while we
  // overwrite it, and the chunks it writes would describe neither version.
  if (doc.hasActiveEmbeddingJob || doc.status === 'pending' || doc.status === 'processing') {
    return {
      editable: false,
      reason: 'This file is being processed. Editing is available once it is ready.',
    };
  }

  if (doc.fileSizeBytes > MAX_EDITABLE_BYTES) {
    return {
      editable: false,
      reason: `Files over ${formatEditableSizeLimit()} cannot be edited here — download it, edit locally, and upload it again.`,
    };
  }

  return { editable: true, reason: null };
}

export function getStorageDocumentEditStateForItem(doc: StorageDocumentItem): StorageEditState {
  return getStorageDocumentEditState({
    fileExtension: doc.fileExtension,
    fileSizeBytes: doc.fileSizeBytes,
    status: String(doc.status),
    hasActiveEmbeddingJob: doc.hasActiveEmbeddingJob,
  });
}
