"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.composeService = void 0;
const path = __importStar(require("path"));
const spawn_1 = require("../utils/spawn");
function composeArgs(composePath, args) {
    const absolutePath = path.resolve(composePath);
    return ['compose', '--project-directory', path.dirname(absolutePath), '-f', absolutePath, ...args];
}
function runCompose(args, composePath, timeout = 120000) {
    const result = (0, spawn_1.spawnCommand)('docker', composeArgs(composePath, args), {
        encoding: 'utf8',
        timeout
    });
    if (result.error) {
        throw result.error;
    }
    if (result.status === null) {
        throw new Error('docker compose command not found. Is Docker installed?');
    }
    if (result.status !== 0) {
        throw new Error(`docker compose failed: ${result.stderr?.trim() || result.stdout?.trim() || 'unknown error'}`);
    }
    return result;
}
function normalizeContainer(input) {
    return {
        Id: String(input.ID ?? input.Id ?? ''),
        Name: String(input.Name ?? ''),
        State: String(input.State ?? ''),
        Status: String(input.Status ?? ''),
        Service: String(input.Service ?? '')
    };
}
function parsePsOutput(stdout) {
    const text = stdout.trim();
    if (!text) {
        return [];
    }
    const parsed = JSON.parse(text);
    if (Array.isArray(parsed)) {
        return parsed.map((item) => normalizeContainer(item));
    }
    return text
        .split(/\r?\n/)
        .filter(Boolean)
        .map((line) => normalizeContainer(JSON.parse(line)));
}
exports.composeService = {
    up(composePath, options) {
        const args = ['up', '-d'];
        if (options?.wait) {
            args.push('--wait');
        }
        if (options?.forceRecreate) {
            args.push('--force-recreate');
        }
        if (options?.noDeps) {
            args.push('--no-deps');
        }
        runCompose(args, composePath);
    },
    down(composePath, options) {
        const args = ['down', '--remove-orphans'];
        if (options?.removeVolumes) {
            args.push('--volumes');
        }
        if (options?.removeImages) {
            args.push('--rmi', 'all');
        }
        runCompose(args, composePath);
    },
    stop(composePath) {
        runCompose(['stop'], composePath);
    },
    restart(composePath) {
        runCompose(['restart'], composePath);
    },
    ps(composePath) {
        const result = runCompose(['ps', '--format', 'json'], composePath, 30000);
        try {
            return parsePsOutput(result.stdout ?? '');
        }
        catch {
            throw new Error('Failed to parse docker compose ps output');
        }
    },
    pull(composePath) {
        runCompose(['pull'], composePath);
    },
    logs(composePath, service) {
        const args = ['logs', '--follow'];
        if (service) {
            args.push(service);
        }
        runCompose(args, composePath, 0);
    }
};
//# sourceMappingURL=docker-compose.js.map