/**
 * 媒体缓存 Hook
 * @module src/hooks/useMediaCache
 * @description 提供媒体缓存管理的 React Hook
 */

import { useState, useCallback, useEffect, useRef } from 'react';
import { mediaCacheManager } from '../infrastructure/cache';
import {
  CacheStats,
  CleanupPolicy,
  CleanupResult,
  MediaType,
  CleanupTrigger,
  DEFAULT_CLEANUP_POLICY,
} from '../infrastructure/cache/types';

/**
 * useMediaCache Hook 返回值类型
 */
export interface UseMediaCacheReturn {
  /** 缓存统计信息 */
  stats: CacheStats | null;
  /** 是否正在清理 */
  isClearing: boolean;
  /** 是否已初始化 */
  isInitialized: boolean;
  /** 加载缓存统计 */
  loadStats: () => void;
  /** 执行清理（手动） */
  cleanup: (policy?: Partial<CleanupPolicy>) => Promise<CleanupResult>;
  /** 清空所有缓存 */
  clearAll: () => Promise<void>;
  /** 清理指定会话的缓存 */
  clearConversation: (conversationId: string) => Promise<CleanupResult>;
  /** 启动定期清理 */
  startPeriodicCleanup: () => void;
  /** 停止定期清理 */
  stopPeriodicCleanup: () => void;
  /** 记录缓存访问（用于 LRU） */
  recordAccess: (key: string) => Promise<void>;
  /** 格式化缓存大小 */
  formatSize: (bytes: number) => string;
  /** 缓存媒体文件 */
  cacheMedia: (
    uri: string,
    type: MediaType,
    options?: {
      conversationId?: string;
      messageId?: string;
      size?: number;
    }
  ) => Promise<string>;
  /** 获取缓存的媒体路径 */
  getCachedMedia: (uri: string, type: MediaType) => Promise<string | null>;
}

/**
 * 媒体缓存 Hook
 * @description 提供缓存统计、清理功能、访问记录等
 * @returns {UseMediaCacheReturn} 缓存管理接口
 * 
 * @example
 * ```tsx
 * function MediaSettings() {
 *   const { stats, cleanup, formatSize } = useMediaCache();
 * 
 *   return (
 *     <View>
 *       <Text>总缓存: {formatSize(stats?.totalSize || 0)}</Text>
 *       <Text>图片: {stats?.imageCount || 0}</Text>
 *       <Text>视频: {stats?.videoCount || 0}</Text>
 *       <Button title="清理缓存" onPress={cleanup} />
 *     </View>
 *   );
 * }
 * ```
 */
export function useMediaCache(): UseMediaCacheReturn {
  const [stats, setStats] = useState<CacheStats | null>(null);
  const [isClearing, setIsClearing] = useState(false);
  const [isInitialized, setIsInitialized] = useState(false);
  const initializedRef = useRef(false);

  /**
   * 加载缓存统计
   */
  const loadStats = useCallback(() => {
    const cacheStats = mediaCacheManager.getCacheStats();
    setStats(cacheStats);
  }, []);

  /**
   * 执行清理
   */
  const cleanup = useCallback(async (policy?: Partial<CleanupPolicy>): Promise<CleanupResult> => {
    setIsClearing(true);
    try {
      // 如果提供了自定义策略，应用它
      // 注意：这里简化处理，实际可能需要合并策略
      const result = await mediaCacheManager.cleanup(CleanupTrigger.MANUAL);
      await loadStats();
      return result;
    } finally {
      setIsClearing(false);
    }
  }, [loadStats]);

  /**
   * 清空所有缓存
   */
  const clearAll = useCallback(async (): Promise<void> => {
    setIsClearing(true);
    try {
      await mediaCacheManager.clearAll();
      await loadStats();
    } finally {
      setIsClearing(false);
    }
  }, [loadStats]);

  /**
   * 清理指定会话的缓存
   */
  const clearConversation = useCallback(async (conversationId: string): Promise<CleanupResult> => {
    setIsClearing(true);
    try {
      const result = await mediaCacheManager.clearConversationMedia(conversationId);
      await loadStats();
      return result;
    } finally {
      setIsClearing(false);
    }
  }, [loadStats]);

  /**
   * 启动定期清理
   */
  const startPeriodicCleanup = useCallback(() => {
    mediaCacheManager.startPeriodicCleanup();
  }, []);

  /**
   * 停止定期清理
   */
  const stopPeriodicCleanup = useCallback(() => {
    mediaCacheManager.stopPeriodicCleanup();
  }, []);

  /**
   * 记录缓存访问
   */
  const recordAccess = useCallback(async (key: string): Promise<void> => {
    await mediaCacheManager.recordAccess(key);
  }, []);

  /**
   * 缓存媒体文件
   */
  const cacheMedia = useCallback(async (
    uri: string,
    type: MediaType,
    options?: {
      conversationId?: string;
      messageId?: string;
      size?: number;
    }
  ): Promise<string> => {
    const localPath = await mediaCacheManager.cacheMedia(uri, type, options);
    await loadStats();
    return localPath;
  }, [loadStats]);

  /**
   * 获取缓存的媒体路径
   */
  const getCachedMedia = useCallback(async (uri: string, type: MediaType): Promise<string | null> => {
    return await mediaCacheManager.getCachedMedia(uri, type);
  }, []);

  /**
   * 格式化缓存大小
   */
  const formatSize = useCallback((bytes: number): string => {
    if (bytes < 1024) {
      return `${bytes} B`;
    }
    if (bytes < 1024 * 1024) {
      return `${(bytes / 1024).toFixed(1)} KB`;
    }
    if (bytes < 1024 * 1024 * 1024) {
      return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
    }
    return `${(bytes / 1024 / 1024 / 1024).toFixed(1)} GB`;
  }, []);

  /**
   * 初始化
   */
  useEffect(() => {
    const initialize = async () => {
      if (initializedRef.current) return;
      initializedRef.current = true;

      try {
        await mediaCacheManager.initialize();
        setIsInitialized(true);
        loadStats();
      } catch (error) {
        console.error('[useMediaCache] 初始化失败:', error);
        // 即使初始化失败，也允许使用基本功能
        setIsInitialized(true);
        loadStats();
      }
    };

    initialize();

    // 清理函数
    return () => {
      // 停止定期清理
      mediaCacheManager.stopPeriodicCleanup();
    };
  }, [loadStats]);

  return {
    stats,
    isClearing,
    isInitialized,
    loadStats,
    cleanup,
    clearAll,
    clearConversation,
    startPeriodicCleanup,
    stopPeriodicCleanup,
    recordAccess,
    formatSize,
    cacheMedia,
    getCachedMedia,
  };
}
