import { apiClient } from "./client";

export interface ProjectCreatePayload {
  name: string;
  description?: string;
  style?: string;
  aspectRatio?: string;
  resolution?: string;
}

export interface ProjectUpdatePayload {
  name?: string;
  description?: string;
  style?: string;
  aspectRatio?: string;
  resolution?: string;
}

export interface ProjectDTO {
  id: string;
  name: string;
  description?: string;
  status: "draft" | "processing" | "completed" | "failed";
  style?: string;
  aspectRatio?: string;
  resolution?: string;
  coverUrl?: string;
  assetCount: number;
  createdAt: string;
  updatedAt: string;
}

export interface AssetDTO {
  id: string;
  projectId: string;
  name: string;
  originalName: string;
  assetType: string;
  mimeType?: string;
  fileSize?: number;
  url: string;
  createdAt: string;
}

export interface ScriptInfoDTO {
  title: string;
  genre: string;
  synopsis: string;
  episodeCount: number;
  characterCount: number;
  sceneCount: number;
  storyboardCount: number;
}

const wrap = <T>(r: { data: { data: T } }) => r.data.data;

export const projectsApi = {
  create: (p: ProjectCreatePayload) =>
    apiClient.post<{ data: ProjectDTO }>("/projects", p).then(wrap),

  list: () =>
    apiClient.get<{ data: ProjectDTO[] }>("/projects").then(wrap),

  get: (id: string) =>
    apiClient.get<{ data: ProjectDTO }>(`/projects/${id}`).then(wrap),

  update: (id: string, p: ProjectUpdatePayload) =>
    apiClient.put<{ data: ProjectDTO }>(`/projects/${id}`, p).then(wrap),

  delete: (id: string) =>
    apiClient.delete(`/projects/${id}`),

  uploadAsset: (projectId: string, file: File, assetType = "other") => {
    const form = new FormData();
    form.append("file", file);
    // Content-Type 设为 undefined 以清除实例默认的 application/json，
    // 让浏览器 XHR 检测到 FormData 后自动添加带 boundary 的 multipart/form-data
    return apiClient
      .post<{ data: AssetDTO }>(
        `/projects/${projectId}/assets?assetType=${assetType}`,
        form,
        { headers: { "Content-Type": undefined }, timeout: 600_000 }
      )
      .then(wrap);
  },

  listAssets: (projectId: string) =>
    apiClient.get<{ data: AssetDTO[] }>(`/projects/${projectId}/assets`).then(wrap),

  deleteAsset: (projectId: string, assetId: string) =>
    apiClient.delete(`/projects/${projectId}/assets/${assetId}`),

  /** 服务端代理读取剧本文本内容，避免前端直接请求 TOS 跨域 */
  readScriptContent: (projectId: string): Promise<string> =>
    apiClient
      .get<{ data: { content: string } }>(`/projects/${projectId}/assets/script/content`)
      .then((r) => r.data.data.content),

  /** 解析已上传的剧本 doc/docx，返回结构化摘要（不写库，用于预览） */
  parseScript: (projectId: string): Promise<ScriptInfoDTO> =>
    apiClient
      .get<{ data: ScriptInfoDTO }>(`/projects/${projectId}/assets/script/parse`, {
        timeout: 600_000,
      })
      .then(wrap),

  /** 一键导入：解析并写入大纲、分集、角色、场景、分镜 */
  importScript: (projectId: string): Promise<ScriptInfoDTO> =>
    apiClient
      .post<{ data: ScriptInfoDTO }>(
        `/projects/${projectId}/assets/script/import`,
        undefined,
        { timeout: 600_000 }
      )
      .then(wrap),
};
