"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.getProjectConfigPath = getProjectConfigPath;
exports.readProjectConfig = readProjectConfig;
exports.loadProjectConfig = loadProjectConfig;
exports.hasConfiguredCloudConnection = hasConfiguredCloudConnection;
exports.maskCloudToken = maskCloudToken;
exports.writeProjectConfig = writeProjectConfig;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
function normalizeCloudConfig(value) {
    if (value === undefined) {
        return undefined;
    }
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return undefined;
    }
    const typed = value;
    if (typed.token !== undefined && typeof typed.token !== 'string') {
        return undefined;
    }
    if (typed.server !== undefined && typeof typed.server !== 'string') {
        return undefined;
    }
    if (typed.appBaseUrl !== undefined && typeof typed.appBaseUrl !== 'string') {
        return undefined;
    }
    if (typed.uploadOnValidate !== undefined &&
        typeof typed.uploadOnValidate !== 'boolean') {
        return undefined;
    }
    if (typed.organization !== undefined && typeof typed.organization !== 'string') {
        return undefined;
    }
    if (typed.organizationName !== undefined && typeof typed.organizationName !== 'string') {
        return undefined;
    }
    if (typed.organizationSlug !== undefined && typeof typed.organizationSlug !== 'string') {
        return undefined;
    }
    if (typed.planName !== undefined && typeof typed.planName !== 'string') {
        return undefined;
    }
    if (typed.validatedAt !== undefined && typeof typed.validatedAt !== 'string') {
        return undefined;
    }
    if (typed.tokenLabel !== undefined && typeof typed.tokenLabel !== 'string') {
        return undefined;
    }
    if (typed.tokenLast4 !== undefined && typeof typed.tokenLast4 !== 'string') {
        return undefined;
    }
    if (typed.lastUploadAt !== undefined && typeof typed.lastUploadAt !== 'string') {
        return undefined;
    }
    const normalized = {
        ...(typeof typed.server === 'string' && typed.server.trim().length > 0
            ? { server: typed.server.trim() }
            : {}),
        ...(typeof typed.token === 'string' && typed.token.trim().length > 0
            ? { token: typed.token.trim() }
            : {}),
        ...(typeof typed.appBaseUrl === 'string' && typed.appBaseUrl.trim().length > 0
            ? { appBaseUrl: typed.appBaseUrl.trim() }
            : {}),
        ...(typeof typed.uploadOnValidate === 'boolean'
            ? { uploadOnValidate: typed.uploadOnValidate }
            : {}),
        ...(typeof typed.organization === 'string' && typed.organization.trim().length > 0
            ? { organization: typed.organization.trim() }
            : {}),
        ...(typeof typed.organizationName === 'string' && typed.organizationName.trim().length > 0
            ? { organizationName: typed.organizationName.trim() }
            : {}),
        ...(typeof typed.organizationSlug === 'string' && typed.organizationSlug.trim().length > 0
            ? { organizationSlug: typed.organizationSlug.trim() }
            : {}),
        ...(typeof typed.planName === 'string' && typed.planName.trim().length > 0
            ? { planName: typed.planName.trim() }
            : {}),
        ...(typeof typed.validatedAt === 'string' && typed.validatedAt.trim().length > 0
            ? { validatedAt: typed.validatedAt.trim() }
            : {}),
        ...(typeof typed.tokenLabel === 'string' && typed.tokenLabel.trim().length > 0
            ? { tokenLabel: typed.tokenLabel.trim() }
            : {}),
        ...(typeof typed.tokenLast4 === 'string' && typed.tokenLast4.trim().length > 0
            ? { tokenLast4: typed.tokenLast4.trim() }
            : {}),
        ...(typeof typed.lastUploadAt === 'string' && typed.lastUploadAt.trim().length > 0
            ? { lastUploadAt: typed.lastUploadAt.trim() }
            : {}),
    };
    return Object.keys(normalized).length > 0 ? normalized : undefined;
}
function normalizeProjectConfig(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return {};
    }
    const typed = value;
    if (typed.policySource !== undefined && typeof typed.policySource !== 'string') {
        return undefined;
    }
    if (typed.cloud !== undefined) {
        const normalizedCloud = normalizeCloudConfig(typed.cloud);
        if (typed.cloud !== undefined && !normalizedCloud && typed.cloud !== null) {
            return undefined;
        }
    }
    const normalizedCloud = normalizeCloudConfig(typed.cloud);
    return {
        ...(typeof typed.policySource === 'string' && typed.policySource.trim().length > 0
            ? { policySource: typed.policySource.trim() }
            : {}),
        ...(normalizedCloud ? { cloud: normalizedCloud } : {}),
    };
}
function getProjectConfigPath(workspaceRoot) {
    return path.join(workspaceRoot, '.archpilot', 'config.json');
}
async function readProjectConfig(workspaceRoot) {
    const configPath = getProjectConfigPath(workspaceRoot);
    let contents;
    try {
        contents = await node_fs_1.promises.readFile(configPath, { encoding: 'utf8' });
    }
    catch (error) {
        if (error.code === 'ENOENT') {
            return { invalidJson: false };
        }
        return {
            invalidJson: true,
            errorMessage: error instanceof Error ? error.message : 'Unable to read .archpilot/config.json.',
        };
    }
    try {
        const parsed = JSON.parse(contents);
        const normalized = normalizeProjectConfig(parsed);
        if (!normalized) {
            return {
                invalidJson: true,
                errorMessage: 'ArchPilot project config is invalid: .archpilot/config.json must be a JSON object. policySource must be a string when provided. cloud must be an object, cloud.server/cloud.token/cloud.appBaseUrl/cloud.organization/cloud.organizationName/cloud.organizationSlug/cloud.planName/cloud.validatedAt/cloud.tokenLabel/cloud.tokenLast4/cloud.lastUploadAt must be strings, and cloud.uploadOnValidate must be a boolean when provided.',
            };
        }
        return {
            config: normalized,
            invalidJson: false,
        };
    }
    catch {
        return {
            invalidJson: true,
            errorMessage: 'ArchPilot project config is invalid JSON. Please fix .archpilot/config.json.',
        };
    }
}
async function loadProjectConfig(workspaceRoot) {
    const loaded = await readProjectConfig(workspaceRoot);
    return loaded.config;
}
function hasConfiguredCloudConnection(config) {
    const cloud = config?.cloud;
    return !!(cloud?.token ||
        cloud?.tokenLast4 ||
        cloud?.validatedAt ||
        cloud?.organization ||
        cloud?.organizationName ||
        cloud?.organizationSlug);
}
function maskCloudToken(token) {
    if (!token) {
        return 'not stored';
    }
    if (token.length <= 8) {
        return `${'*'.repeat(Math.max(0, token.length - 2))}${token.slice(-2)}`;
    }
    return `${token.slice(0, 4)}...${token.slice(-4)}`;
}
async function writeProjectConfig(workspaceRoot, config) {
    const configPath = getProjectConfigPath(workspaceRoot);
    const normalized = normalizeProjectConfig(config) ?? {};
    if (Object.keys(normalized).length === 0) {
        await node_fs_1.promises.rm(configPath, { force: true }).catch(() => undefined);
        return;
    }
    await node_fs_1.promises.mkdir(path.dirname(configPath), { recursive: true });
    await node_fs_1.promises.writeFile(configPath, `${JSON.stringify(normalized, null, 2)}\n`, {
        encoding: 'utf8',
    });
}
//# sourceMappingURL=projectConfig.js.map