import type { QualityComponentCatalog } from '#/components/quality';

import { requestClient } from '#/api/request';

export namespace QcReportAiApi {
  /** 一个组件草稿：结构完全扁平，没有 children */
  export interface DraftComponent {
    type?: string;
    /** 组件属性；后端已按积木清单过滤掉未声明的 key */
    props?: Record<string, unknown>;
  }

  /** AI 猜出的纸张配置，可能为空（为空表示沿用当前模板的纸张） */
  export interface DraftPage {
    size?: string;
    orientation?: string;
    margin?: { top?: number; right?: number; bottom?: number; left?: number };
  }

  /**
   * 识别结果：一份模板草稿，**尚未落库**。
   * <p>
   * 需人工到设计器确认并点「保存」，才会写成模板版本。
   */
  export interface DraftResp {
    components?: DraftComponent[];
    page?: DraftPage;
    /** AI 对这份文档的一句话说明 */
    summary?: string;
    /** 软提示：被跳过的页、无法表达的区块等，必须展示给用户 */
    warnings?: string[];
    durationMs?: number;
  }

  export interface DraftReq {
    /**
     * 上传文件对应的 blobId，**顺序即文档页序**。
     * <p>
     * 文件先经 /system/storage-blob/upload 上传取得 blobId；业务模块不自建上传通道。
     */
    blobIds: number[];
    /** 目标模板编号，用于日志留痕与附件归属 */
    templateId: number;
    /** 必须与设计器一致，两端不匹配时后端直接报错 */
    schemaVersion: string;
    /** 积木清单，由 buildQualityComponentCatalog() 从活注册表生成 */
    catalog: QualityComponentCatalog[];
    /** 用户补充说明，拼进提示词帮助模型理解文档 */
    hint?: string;
  }
}

/**
 * 识别文件生成模板草稿。
 * <p>
 * 同步返回且不落库，所以单独放宽超时。这个值必须比后端的耗时预算更宽：
 * 后端 `yudao.qcreport.ai-import.max-duration-seconds`（默认 180 秒，只在两次模型调用之间检查）
 * 加上单次调用超时 `yudao.ai.timeout`（默认 60 秒），最坏 240 秒。
 * 掐得比它早，用户看到的是「请求超时」这种没有指向的报错，
 * 而后端本来能给出「哪一步、为什么、怎么办」的明确提示。
 */
export function generateAiDraft(data: QcReportAiApi.DraftReq) {
  return requestClient.post<QcReportAiApi.DraftResp>(
    '/qc-report/ai-import/draft',
    data,
    { timeout: 300_000 },
  );
}
