/**
 * Workspace Config (config.json) Management
 *
 * Reads and writes settings from .proletariat/config.json.
 * This is distinct from execution config (stored in database).
 *
 * Config structure:
 * {
 *   "type": "hq",
 *   "name": "workspace-name",
 *   "version": "1.0.0",
 *   "schemaVersion": 1,
 *   "prlt": {
 *     "channel": "npm" | "npm:dev" | "gh" | "gh:dev" | "mount"
 *   }
 * }
 */
import * as fs from 'node:fs';
import * as path from 'node:path';
/**
 * Read workspace config from .proletariat/config.json
 */
export function readWorkspaceConfig(hqPath) {
    const configPath = path.join(hqPath, '.proletariat', 'config.json');
    if (!fs.existsSync(configPath)) {
        return null;
    }
    try {
        const content = fs.readFileSync(configPath, 'utf-8');
        return JSON.parse(content);
    }
    catch {
        return null;
    }
}
/**
 * Write workspace config to .proletariat/config.json
 */
export function writeWorkspaceConfig(hqPath, config) {
    const configPath = path.join(hqPath, '.proletariat', 'config.json');
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
}
/**
 * Get prlt config from workspace, with defaults
 */
export function getPrltConfig(hqPath) {
    const config = readWorkspaceConfig(hqPath);
    return config?.prlt ?? {};
}
/**
 * Update prlt config section
 */
export function updatePrltConfig(hqPath, prltConfig) {
    const config = readWorkspaceConfig(hqPath);
    if (!config) {
        throw new Error('No workspace config found');
    }
    config.prlt = {
        ...config.prlt,
        ...prltConfig,
    };
    writeWorkspaceConfig(hqPath, config);
}
/**
 * Get the prlt channel to use for container builds.
 * Priority: override > workspace config > default "npm"
 */
export function getPrltChannel(hqPath, override) {
    if (override) {
        return override;
    }
    const prltConfig = getPrltConfig(hqPath);
    return prltConfig.channel ?? 'npm';
}
/**
 * Parse a prlt channel string into registry and version components.
 * Examples:
 *   "npm" -> { registry: "npm", version: "latest" }
 *   "npm:dev" -> { registry: "npm", version: "dev" }
 *   "npm:1.2.3" -> { registry: "npm", version: "1.2.3" }
 *   "gh" -> { registry: "gh", version: "latest" }
 *   "gh:dev" -> { registry: "gh", version: "dev" }
 *   "mount" -> { registry: "mount", version: null }
 */
export function parseChannel(channel) {
    if (channel === 'mount') {
        return { registry: 'mount', version: null };
    }
    if (channel.startsWith('gh')) {
        const version = channel.includes(':') ? channel.split(':')[1] : 'latest';
        return { registry: 'gh', version };
    }
    // Default to npm
    if (channel.startsWith('npm')) {
        const version = channel.includes(':') ? channel.split(':')[1] : 'latest';
        return { registry: 'npm', version };
    }
    // Bare version numbers default to npm
    return { registry: 'npm', version: channel };
}
//# sourceMappingURL=workspace-config.js.map