import request from "../utils/request";
import {AiTaskStatuses, TaskStatuses} from "~/types";
import {UnauthorizedError} from "~/types";
import useUser from "~/store/user";

/** 最近一次 create_task 失败原因（供上传组件 toast），成功时会清空 */
export const tsCreateTaskLastError: { message?: string } = {};

export default function useTask() {

    async function createTask(data: any): Promise<string | undefined> {
        try {
            const out = await request({
                url: '/api/v2/ts/create_task', method: 'POST', data
            });
            const {r, d, e} = out;
            if (r) {
                tsCreateTaskLastError.message = undefined;
                return d;
            }
            const errText = typeof e === 'string' && e.length ? e : `HTTP ${(out as { statusCode?: number }).statusCode ?? '?'}`;
            tsCreateTaskLastError.message = errText;
            console.error('[createTask] TS 返回失败', { data, r, d, e, statusCode: (out as { statusCode?: number }).statusCode });
            // if sudo token failed, retry
            if (d === UnauthorizedError.HtySudoerTokenErr) {
                return useUser().sudo2().then(() => createTask(data))
            }
        } catch (err) {
            const msg = typeof err === 'object' && err && 'e' in err && typeof (err as { e?: string }).e === 'string'
                ? (err as { e: string }).e
                : String(err);
            tsCreateTaskLastError.message = msg;
            console.error('[createTask] 请求异常', err)
        }
    }

    async function getTask(taskId: string) {
        if (!taskId || !/\w{8}(-\w{4}){3}-\w{12}/.test(taskId)) return;
        const {r, d, e} = await request({url: `/api/v2/ts/task/${taskId}`});
        if (r) {
            return d;
        }
    }

    async function getTaskStatus(taskId: string) {
        if (!taskId || !/\w{8}(-\w{4}){3}-\w{12}/.test(taskId)) return;
        const {r, d, e} = await request({url: `/api/v2/ts/task_status/${taskId}`});
        if (r) {
            return d;
        }
    }

    async function getTaskResource(taskId: string) {
        const {r, d, e} = await request({url: `/api/v1/uc/find_hty_resources_by_task_id/${taskId}`});
        if (r) {
            return d[0];
        }
    }

    function isTaskFinished(task_status?: TaskStatuses | AiTaskStatuses) {
        return [TaskStatuses.DONE, TaskStatuses.FAILED, AiTaskStatuses.SUCCESS].includes(task_status as TaskStatuses)
    }

    return { getTaskStatus, getTaskResource, isTaskFinished, createTask, getTask }
}
