import Docker from 'dockerode';
import fs from 'node:fs';
import path from 'node:path';
import DockerWrapper from './dockerWrapper.js';
export default class LocalDockerWrapper extends DockerWrapper {
    _PING_TIMEOUT_MS = 5000;
    async dispose() {
        // No dispose
    }
    async getDocker() {
        // If DOCKER_HOST is set, let Dockerode use it to override anything else
        if (process.env.DOCKER_HOST) {
            return new Docker();
        }
        // Dockerode doesn't know about colima, so we add a special check for that
        const colimaSocketPath = this.getColimaSocketPath();
        if (colimaSocketPath) {
            return new Docker({ socketPath: colimaSocketPath });
        }
        // Otherwise, revert to Dockerode default
        return new Docker();
    }
    async isAvailable() {
        const docker = await this.get();
        const pingPromise = docker.ping();
        const timeoutPromise = new Promise((_, reject) => {
            setTimeout(() => {
                reject(new Error('Ping timed out'));
            }, this._PING_TIMEOUT_MS);
        });
        try {
            await Promise.race([pingPromise, timeoutPromise]);
            return true;
        }
        catch {
            return false;
        }
    }
    async prepare() {
        // No preparation
    }
    async start() {
        // No start
    }
    getColimaSocketPath() {
        const colimaHome = process.env.COLIMA_HOME ||
            (process.env.HOME ? path.join(process.env.HOME, '.colima') : undefined);
        if (!colimaHome) {
            return;
        }
        const resolvedColimaHome = path.resolve(colimaHome);
        if (!fs.existsSync(resolvedColimaHome)) {
            return;
        }
        const colimaLegacyDockerSockPath = path.join(resolvedColimaHome, 'docker.sock');
        if (fs.existsSync(colimaLegacyDockerSockPath)) {
            return colimaLegacyDockerSockPath;
        }
        const colimaDockerSockPath = path.join(resolvedColimaHome, 'docker', 'docker.sock');
        if (fs.existsSync(colimaDockerSockPath)) {
            return colimaDockerSockPath;
        }
        return undefined;
    }
}
