import { request } from '@kit.BasicServicesKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { fileIo as fs } from '@kit.CoreFileKit';

/**
 * 文件下载
 * @param callback
 * status: 0-默认, 1-进行中(progress为百分比), 2-成功(progress为0, path为路径), -1-失败
 */
export async function downloadFile(
  context: Context,
  url: string,
  fileName: string,
  callback: (status: number, progress: number, path?: string) => void
) {
  const filePath = `${context.filesDir}/${fileName}`;

  try {
    // --- 清理旧文件逻辑 ---
    if (fs.accessSync(filePath)) {
      console.info(`检测到旧文件，正在删除: ${filePath}`);
      fs.unlinkSync(filePath);
    }
  } catch (e) {
    console.error(`删除旧文件失败: ${(e as BusinessError).message}`);
    // 即使删除失败（如文件被占用），通常也可以继续，因为下载配置了 overwrite: true
  }

  let config: request.agent.Config = {
    action: request.agent.Action.DOWNLOAD,
    url: url,
    saveas: filePath,
    mode: request.agent.Mode.FOREGROUND,
    overwrite: true // 即使删除逻辑失败，此参数也会确保覆盖
  };

  try {
    const task = await request.agent.create(context, config);

    task.on('progress', (progress) => {
      if (progress.sizes && progress.sizes.length > 0 && progress.sizes[0] > 0) {
        const percent = Math.floor((progress.processed / progress.sizes[0]) * 100);
        callback(1, percent);
      } else {
        callback(1, 0);
      }
    });

    task.on('completed', () => {
      callback(2, 100, filePath);
    });

    task.on('failed', (info) => {
      console.error(`任务失败详情: ${JSON.stringify(info)}`);
      callback(-1, -1);
    });

    await task.start();
  } catch (error) {
    const err = error as BusinessError;
    console.error(`创建任务失败: ${err.code} ${err.message}`);
    callback(-1, -1);
  }
}


