import type { MindSpaceAsset } from '../types';

const ASSET_ICONS: Record<string, string> = {
  pdf: '📄',
  word: '📝',
  excel: '📊',
  ppt: '📽️',
  image: '🖼️',
  markdown: 'MD',
  html: '🌐',
  file: '📁',
};

const SOURCE_LABELS: Record<MindSpaceAsset['sourceType'], string> = {
  upload: '上传',
  chat: '聊天',
  agent: 'AI 生成',
  workspace: '工作区',
  template: '模板',
  generated: '系统',
};

const PREVIEWABLE_MIME_TYPES = new Set([
  'text/html',
  'text/plain',
  'text/markdown',
  'text/csv',
  'application/pdf',
  'image/png',
  'image/jpeg',
  'image/webp',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
]);

export function assetIcon(asset: MindSpaceAsset) {
  return ASSET_ICONS[asset.assetType] ?? ASSET_ICONS.file;
}

export function assetSourceLabel(asset: MindSpaceAsset) {
  return SOURCE_LABELS[asset.sourceType] ?? '资料';
}

export function isPreviewableAsset(asset: MindSpaceAsset) {
  return (
    asset.status === 'ready' &&
    asset.scanStatus !== 'blocked' &&
    PREVIEWABLE_MIME_TYPES.has(asset.mimeType)
  );
}

export function isWorkAsset(asset: MindSpaceAsset) {
  return asset.assetType === 'html' || asset.mimeType === 'text/html';
}

export function isImageAsset(asset: MindSpaceAsset) {
  return asset.assetType === 'image' || asset.mimeType.startsWith('image/');
}

export function buildAssetImageUrl(asset: Pick<MindSpaceAsset, 'id' | 'updatedAt' | 'publicUrl'>) {
  if (asset.publicUrl) return asset.publicUrl;
  return `/api/mindspace/v1/assets/${asset.id}/download?inline=1&v=${asset.updatedAt}`;
}

export function buildAbsoluteAssetImageUrl(
  asset: Pick<MindSpaceAsset, 'id' | 'updatedAt' | 'publicUrl'>,
): string {
  if (asset.publicUrl) return new URL(asset.publicUrl, window.location.origin).toString();
  return `${window.location.origin}${buildAssetImageUrl(asset)}`;
}

/** Chrome blocks PDF rendering inside any sandboxed iframe. */
export function assetPreviewUsesSandbox(mimeType: string) {
  return mimeType !== 'application/pdf';
}

export const ASSET_PREVIEW_IFRAME_SANDBOX = 'allow-same-origin';

export function buildAssetPreviewFrameConfig(
  asset: Pick<MindSpaceAsset, 'id' | 'mimeType'>,
) {
  if (asset.mimeType === 'application/pdf') {
    return {
      src: `/api/mindspace/v1/assets/${asset.id}/download?inline=1`,
    };
  }
  return {
    src: `/api/mindspace/v1/assets/${asset.id}/preview`,
    sandbox: ASSET_PREVIEW_IFRAME_SANDBOX,
  };
}
