import { client } from '../client';
import type { ScriptShot } from '../types';

export type { ScriptShot };

/**
 * 提示词文件项
 */
interface PromptFileItem {
  filename: string;
  label: string;
  desc: string;
}

/**
 * 大类项
 */
export interface CategoryItem {
  code: string;
  name: string;
  files: PromptFileItem[];
}

/**
 * 生成标题请求参数
 */
interface GenerateTitleParams {
  scriptContent: string;
  titleType: 'main' | 'sub';
  maxLength?: number;
  usage?: 'video' | 'cover';
}

/**
 * 生成标题响应
 */
interface GenerateTitleResponse {
  title: string;
}
/**
 * 脚本相关 API
 */
const CATEGORIES_CACHE_KEY = 'script-categories-v2';

export const scriptApi = {
  /**
   * 获取提示词分类列表（直接请求）
   * GET /script/categories
   */
  getCategories: async (): Promise<CategoryItem[]> => {
    return client.get<CategoryItem[]>('/script/categories');
  },

  /**
   * 获取提示词分类列表（带本地缓存 + 静默刷新）
   *
   * 使用方式：
   *   const { cached, refresh } = scriptApi.getCategoriesCached();
   *   if (cached) setCategories(cached);     // 立即可见
   *   refresh.then(setCategories);            // 后台更新
   */
  getCategoriesCached: (): {
    cached: CategoryItem[] | null;
    refresh: Promise<CategoryItem[]>;
  } => {
    let cached: CategoryItem[] | null = null;
    const raw = localStorage.getItem(CATEGORIES_CACHE_KEY);
    if (raw) {
      try {
        const parsed = JSON.parse(raw);
        cached = parsed.data;
      } catch { /* 缓存损坏，忽略 */ }
    }

    const refresh = client.get<CategoryItem[]>('/script/categories').then(data => {
      localStorage.setItem(CATEGORIES_CACHE_KEY, JSON.stringify({ data, ts: Date.now() }));
      return data;
    });

    return { cached, refresh };
  },

  /**
   * 智能生成标题
   * POST /script/generate-title
   *
   * 根据脚本内容生成大标题或小标题
   */
  generateTitle: async (params: GenerateTitleParams): Promise<GenerateTitleResponse> => {
    return client.post<GenerateTitleResponse>('/script/generate-title', {
      script_content: params.scriptContent,
      title_type: params.titleType,
      max_length: params.maxLength,
      usage: params.usage ?? 'video',
    });
  },

  /**
   * AI 润色脚本
   * POST /script/polish
   *
   * @param shotType 镜头类型：'segment'(分镜) 或 'empty_shot'(空镜)，用于画面润色时区分
   */
  polish: async (
    _segmentId: number,
    content: string,
    polishType: 'scene' | 'prompt' | 'voiceover' = 'voiceover',
    shotType: 'segment' | 'empty_shot' = 'segment'
  ): Promise<string> => {
    const backendType = polishType === 'prompt' ? 'scene' : polishType;
    return client.post<string>('/script/polish', {
      content: content,
      polishType: backendType,
      shotType: shotType,
    });
  },
};
