"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.managedMarkdownMarkerPrefix = void 0;
exports.buildManagedMetadata = buildManagedMetadata;
exports.withManagedJsonMetadata = withManagedJsonMetadata;
exports.withManagedMarkdownMarker = withManagedMarkdownMarker;
exports.isManagedJsonArtifact = isManagedJsonArtifact;
exports.isManagedMarkdownArtifact = isManagedMarkdownArtifact;
exports.classifyManagedArtifact = classifyManagedArtifact;
exports.writeManagedArtifactIfSafe = writeManagedArtifactIfSafe;
const path = __importStar(require("node:path"));
const node_fs_1 = require("node:fs");
const packageVersion_1 = require("./packageVersion");
exports.managedMarkdownMarkerPrefix = '<!-- archpilot:managed';
async function buildManagedMetadata(generator, generatedAt = new Date().toISOString()) {
    return {
        managed: true,
        generatedAt,
        generator,
        version: await (0, packageVersion_1.readArchpilotPackageVersion)(),
    };
}
function withManagedJsonMetadata(value, metadata) {
    return {
        xArchPilot: metadata,
        ...value,
    };
}
function withManagedMarkdownMarker(content, metadata) {
    const marker = `${exports.managedMarkdownMarkerPrefix} generated-by=${metadata.generator} -->`;
    const normalized = content.replace(new RegExp(`^${escapeRegExp(exports.managedMarkdownMarkerPrefix)}[^\\n]*\\n`, 'u'), '');
    return `${marker}\n${normalized}`;
}
function isManagedJsonArtifact(value, options) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        return false;
    }
    const metadata = value.xArchPilot;
    if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {
        return false;
    }
    const typedMetadata = metadata;
    if (typedMetadata.managed !== true) {
        return false;
    }
    if (!options?.generator) {
        return true;
    }
    return (typedMetadata.generator === undefined ||
        typedMetadata.generator === options.generator);
}
function isManagedMarkdownArtifact(content) {
    return content.trimStart().startsWith(exports.managedMarkdownMarkerPrefix);
}
async function classifyManagedArtifact(workspaceRoot, relativePath, kind, options) {
    const absolutePath = path.join(workspaceRoot, ...relativePath.split('/'));
    let content;
    try {
        content = await node_fs_1.promises.readFile(absolutePath, { encoding: 'utf8' });
    }
    catch (error) {
        if (error.code === 'ENOENT') {
            return {
                relativePath,
                status: 'create',
                reason: 'file is missing',
            };
        }
        throw error;
    }
    if (kind === 'markdown') {
        return isManagedMarkdownArtifact(content)
            ? {
                relativePath,
                status: 'update-managed',
                reason: 'file has ArchPilot managed marker',
            }
            : {
                relativePath,
                status: 'preserve-user-owned',
                reason: 'file has no ArchPilot managed marker',
            };
    }
    try {
        const parsed = JSON.parse(content);
        return isManagedJsonArtifact(parsed, options)
            ? {
                relativePath,
                status: 'update-managed',
                reason: 'file has xArchPilot.managed metadata',
            }
            : {
                relativePath,
                status: 'preserve-user-owned',
                reason: 'file has no xArchPilot.managed metadata',
            };
    }
    catch {
        return {
            relativePath,
            status: 'preserve-user-owned',
            reason: 'file is not valid JSON',
        };
    }
}
async function writeManagedArtifactIfSafe(workspaceRoot, plan, content) {
    if (plan.status === 'preserve-user-owned') {
        return false;
    }
    const absolutePath = path.join(workspaceRoot, ...plan.relativePath.split('/'));
    await node_fs_1.promises.mkdir(path.dirname(absolutePath), { recursive: true });
    await node_fs_1.promises.writeFile(absolutePath, content, { encoding: 'utf8' });
    return true;
}
function escapeRegExp(value) {
    return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
}
//# sourceMappingURL=managedArtifacts.js.map