import { request, FormData } from 'undici';
import { Blob } from 'node:buffer';
import { t } from './i18n/translate.js';
export class TEClient {
    opts;
    constructor(opts) {
        this.opts = opts;
    }
    url(p) {
        return this.opts.host.replace(/\/$/, '') + p;
    }
    assertOk(env) {
        if (env.return_code !== 0) {
            if (env.return_code === -1001) {
                throw new Error(t('auth.token_expired_api'));
            }
            throw new Error(env.return_message || t('error.ae_error', { code: env.return_code }));
        }
    }
    async getProgram(projectId) {
        const r = await request(this.url(`/v1/ta/bury/manage/program/query?projectId=${encodeURIComponent(String(projectId))}`), {
            method: 'GET',
            headers: {
                authorization: `bearer ${this.opts.token}`,
                accept: 'application/json',
            },
        });
        const env = (await r.body.json());
        this.assertOk(env);
        return env.data ?? null;
    }
    async deleteProgram(projectId) {
        const r = await request(this.url(`/v1/ta/bury/manage/program/delete?projectId=${encodeURIComponent(String(projectId))}`), {
            method: 'GET',
            headers: {
                authorization: `bearer ${this.opts.token}`,
                accept: 'application/json',
            },
        });
        const env = (await r.body.json());
        this.assertOk(env);
        return { return_code: env.return_code, return_message: env.return_message };
    }
    async uploadProgramExcel(args) {
        const fd = new FormData();
        fd.append('file', new Blob([new Uint8Array(args.file)], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), args.filename);
        fd.append('projectId', String(args.projectId));
        fd.append('access_token', this.opts.token);
        const r = await request(this.url('/v1/ta/bury/manage/program/excel-save'), {
            method: 'POST',
            body: fd,
        });
        const env = (await r.body.json());
        this.assertOk(env);
        return { return_code: env.return_code, return_message: env.return_message };
    }
    /** 获取 AE 用户配置（含语言设置 umi_locale） */
    async getAEConfig() {
        const r = await request(this.url(`/v1/ta/auto/config/getUserAutoConfig?@t=${Date.now()}`), {
            method: 'GET',
            headers: {
                authorization: `bearer ${this.opts.token}`,
                'x-requested-with': 'XMLHttpRequest',
                accept: 'application/json',
            },
        });
        const env = (await r.body.json());
        this.assertOk(env);
        return env.data ?? null;
    }
    /** 切换 AE 语言（lang 格式：en_US, zh_CN, ja_JP, ko_KR） */
    async setAELang(langCode) {
        await request(this.url(`/v1/ta/auto/config/getUserAutoConfig?@t=${Date.now()}&lang=${encodeURIComponent(langCode)}`), {
            method: 'GET',
            headers: {
                authorization: `bearer ${this.opts.token}`,
                'x-requested-with': 'XMLHttpRequest',
                accept: 'application/json',
            },
        });
    }
}
