import * as path from 'path';
import * as fs from 'fs';
import * as os from 'os';
import { Logger } from './logger.js';
/**
 * Handles file download lifecycle from the browser.
 */
export class DownloadHandler {
    static downloadDir = path.join(os.tmpdir(), 'antigravity-downloads');
    /**
     * Saves a Playwright Download object to the local temp directory.
     * Returns the absolute path of the saved file.
     */
    static async capture(download) {
        if (!fs.existsSync(this.downloadDir)) {
            fs.mkdirSync(this.downloadDir, { recursive: true });
        }
        const fileName = download.suggestedFilename();
        const filePath = path.join(this.downloadDir, `${Date.now()}_${fileName}`);
        Logger.log(`Capturing download: ${fileName} -> ${filePath}`);
        await download.saveAs(filePath);
        return filePath;
    }
    /**
     * Cleans up a temporary file.
     */
    static cleanup(filePath) {
        try {
            if (fs.existsSync(filePath)) {
                fs.unlinkSync(filePath);
                Logger.log(`Cleaned up temp file: ${filePath}`);
            }
        }
        catch (err) {
            Logger.error(`Failed to cleanup file: ${filePath}`, err);
        }
    }
}
