"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.networkService = void 0;
const spawn_1 = require("../utils/spawn");
function runDocker(args) {
    const result = (0, spawn_1.spawnCommand)('docker', args, {
        encoding: 'utf8',
        timeout: 30000
    });
    if (result.error) {
        throw result.error;
    }
    if (result.status === null) {
        throw new Error('docker command not found. Is Docker installed?');
    }
    return result;
}
exports.networkService = {
    createNetwork(name, driver = 'bridge') {
        const result = runDocker(['network', 'create', '--driver', driver, name]);
        if (result.status !== 0) {
            throw new Error(`Failed to create network '${name}': ${result.stderr?.trim() || 'unknown error'}`);
        }
    },
    exists(name) {
        try {
            const result = runDocker(['network', 'inspect', name]);
            return result.status === 0 && Boolean(result.stdout?.trim());
        }
        catch {
            return false;
        }
    },
    removeNetwork(name) {
        const result = runDocker(['network', 'rm', name]);
        if (result.status !== 0) {
            throw new Error(`Failed to remove network '${name}': ${result.stderr?.trim() || 'unknown error'}`);
        }
    },
    list() {
        const result = runDocker(['network', 'ls', '--no-trunc', '--format', '{{json .}}']);
        if (result.status !== 0) {
            throw new Error(`Failed to list networks: ${result.stderr?.trim() || 'unknown error'}`);
        }
        return (result.stdout ?? '')
            .trim()
            .split(/\r?\n/)
            .filter(Boolean)
            .map((line) => JSON.parse(line))
            .map((item) => ({
            Name: item.Name ?? '',
            Id: item.ID ?? item.Id ?? '',
            Driver: item.Driver ?? '',
            Scope: item.Scope ?? ''
        }));
    }
};
//# sourceMappingURL=docker-network.js.map