"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.readProjectIdentity = readProjectIdentity;
exports.loadProjectIdentity = loadProjectIdentity;
exports.getProjectIdentityPath = getProjectIdentityPath;
exports.buildDefaultProjectIdentityTemplate = buildDefaultProjectIdentityTemplate;
exports.ensureProjectIdentityFile = ensureProjectIdentityFile;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
function normalizeProjectIdentity(value) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return undefined;
    }
    const typed = value;
    if (typeof typed.repositoryId !== 'string' || typed.repositoryId.trim().length === 0) {
        return undefined;
    }
    if (typed.organizationId !== undefined && typeof typed.organizationId !== 'string') {
        return undefined;
    }
    if (typed.projectKey !== undefined && typeof typed.projectKey !== 'string') {
        return undefined;
    }
    if (typed.team !== undefined && typeof typed.team !== 'string') {
        return undefined;
    }
    if (typed.system !== undefined && typeof typed.system !== 'string') {
        return undefined;
    }
    if (typed.repositoryUrl !== undefined && typeof typed.repositoryUrl !== 'string') {
        return undefined;
    }
    if (typed.defaultBranch !== undefined && typeof typed.defaultBranch !== 'string') {
        return undefined;
    }
    return {
        repositoryId: typed.repositoryId.trim(),
        ...(typeof typed.organizationId === 'string' && typed.organizationId.trim().length > 0
            ? { organizationId: typed.organizationId.trim() }
            : {}),
        ...(typeof typed.projectKey === 'string' && typed.projectKey.trim().length > 0
            ? { projectKey: typed.projectKey.trim() }
            : {}),
        ...(typeof typed.team === 'string' && typed.team.trim().length > 0
            ? { team: typed.team.trim() }
            : {}),
        ...(typeof typed.system === 'string' && typed.system.trim().length > 0
            ? { system: typed.system.trim() }
            : {}),
        ...(typeof typed.repositoryUrl === 'string' && typed.repositoryUrl.trim().length > 0
            ? { repositoryUrl: typed.repositoryUrl.trim() }
            : {}),
        ...(typeof typed.defaultBranch === 'string' && typed.defaultBranch.trim().length > 0
            ? { defaultBranch: typed.defaultBranch.trim() }
            : {}),
    };
}
async function readProjectIdentity(workspaceRoot) {
    const configPath = path.join(workspaceRoot, '.archpilot', 'project.json');
    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/project.json.',
        };
    }
    try {
        const parsed = JSON.parse(contents);
        const normalized = normalizeProjectIdentity(parsed);
        if (!normalized) {
            return {
                invalidJson: true,
                errorMessage: 'ArchPilot project identity config is invalid: .archpilot/project.json must be a JSON object with a non-empty repositoryId string. organizationId/projectKey/team/system/repositoryUrl/defaultBranch must be strings when provided.',
            };
        }
        return {
            identity: normalized,
            invalidJson: false,
        };
    }
    catch {
        return {
            invalidJson: true,
            errorMessage: 'ArchPilot project identity config is invalid JSON. Please fix .archpilot/project.json.',
        };
    }
}
async function loadProjectIdentity(workspaceRoot) {
    const loaded = await readProjectIdentity(workspaceRoot);
    return loaded.identity;
}
function getProjectIdentityPath(workspaceRoot) {
    return path.join(workspaceRoot, '.archpilot', 'project.json');
}
function buildDefaultProjectIdentityTemplate(input) {
    return `${JSON.stringify({
        repositoryId: input.repositoryId,
        organizationId: '',
        projectKey: '',
        team: '',
        system: '',
        repositoryUrl: '',
        defaultBranch: 'main',
    }, null, 2)}\n`;
}
async function ensureProjectIdentityFile(workspaceRoot, input) {
    const configPath = getProjectIdentityPath(workspaceRoot);
    await node_fs_1.promises.mkdir(path.dirname(configPath), { recursive: true });
    try {
        await node_fs_1.promises.access(configPath);
        return { path: configPath, created: false };
    }
    catch {
        // Missing file; create deterministic template.
    }
    await node_fs_1.promises.writeFile(configPath, buildDefaultProjectIdentityTemplate(input), {
        encoding: 'utf8',
    });
    return { path: configPath, created: true };
}
//# sourceMappingURL=projectIdentity.js.map