"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.previewArchitectureSetupRefresh = previewArchitectureSetupRefresh;
exports.applyArchitectureSetupRefresh = applyArchitectureSetupRefresh;
const architectureMap_1 = require("./architectureMap");
const architectureInit_1 = require("./architectureInit");
const architectureMapReporter_1 = require("./reporting/architectureMapReporter");
const managedArtifacts_1 = require("./managedArtifacts");
const smartInit_1 = require("./smartInit");
async function previewArchitectureSetupRefresh(workspaceRoot, options) {
    return buildSetupRefreshResult(workspaceRoot, false, options);
}
async function applyArchitectureSetupRefresh(workspaceRoot, options) {
    return buildSetupRefreshResult(workspaceRoot, true, options);
}
async function buildSetupRefreshResult(workspaceRoot, apply, options) {
    const totalStarted = Date.now();
    const timings = [];
    const measure = async (phase, run) => {
        const started = Date.now();
        try {
            return await run();
        }
        finally {
            timings.push({ phase, durationMs: Date.now() - started });
        }
    };
    const generatedAtUtc = options?.generatedAtUtc ?? new Date().toISOString();
    const metadata = await measure('metadata', () => (0, managedArtifacts_1.buildManagedMetadata)('setup-refresh', generatedAtUtc));
    const contract = await measure('architecture-contract-load', () => (0, architectureInit_1.loadArchitectureContract)(workspaceRoot));
    const detectedArchitecture = contract
        ? {
            components: normalizeConfiguredComponents(contract.components),
            resources: normalizeConfiguredResources(contract.resources),
        }
        : await measure('smart-init-detection', async () => {
            const detection = (0, smartInit_1.detectSmartInit)(workspaceRoot);
            const proposal = detection.proposal ?? (0, smartInit_1.buildArchitectureProposal)(detection);
            return {
                components: proposal.components ?? [],
                resources: proposal.resources ?? [],
            };
        });
    const mapTimings = [];
    const map = await measure('architecture-map-generation', () => (0, architectureMap_1.generateArchitectureMap)(workspaceRoot, {
        generatedAtUtc,
        metadata,
        onTiming: (timing) => mapTimings.push(timing),
    }));
    timings.push(...mapTimings);
    const artifacts = await measure('artifact-rendering', async () => buildGeneratedArtifacts(map));
    const artifactPlans = await measure('file-comparison', () => Promise.all(artifacts.map((artifact) => (0, managedArtifacts_1.classifyManagedArtifact)(workspaceRoot, artifact.relativePath, artifact.kind))));
    const writtenArtifacts = [];
    if (apply) {
        await measure('apply-writes', async () => {
            for (const [index, artifact] of artifacts.entries()) {
                const plan = artifactPlans[index];
                if (!plan) {
                    continue;
                }
                if (await (0, managedArtifacts_1.writeManagedArtifactIfSafe)(workspaceRoot, plan, artifact.content)) {
                    writtenArtifacts.push(artifact.relativePath);
                }
            }
        });
    }
    timings.push({ phase: 'total', durationMs: Date.now() - totalStarted });
    return {
        applied: apply,
        writtenArtifacts,
        generatedAtUtc,
        modules: map.modules.map((moduleEntry) => ({
            name: moduleEntry.moduleName,
            path: moduleEntry.sourcePath,
            exists: moduleEntry.sourcePathExists,
        })),
        components: detectedArchitecture.components.map((component, index) => ({
            id: component.id ?? `component-${index + 1}`,
            ...(component.name ? { name: component.name } : {}),
            ...(component.path ? { path: component.path } : {}),
            ...(component.kind ? { kind: component.kind } : {}),
            ...(component.type ? { type: component.type } : {}),
        })),
        resources: detectedArchitecture.resources.map((resource, index) => ({
            id: resource.id ?? `resource-${index + 1}`,
            ...(resource.name ? { name: resource.name } : {}),
            ...(resource.type ? { type: resource.type } : {}),
            ...(resource.path ? { path: resource.path } : {}),
        })),
        removedOrMissingPaths: map.modules
            .filter((moduleEntry) => !moduleEntry.sourcePathExists)
            .map((moduleEntry) => ({
            name: moduleEntry.moduleName,
            path: moduleEntry.sourcePath,
        })),
        dependencyEdges: map.edges,
        artifacts: artifactPlans,
        userOwnedFilesPreserved: artifactPlans
            .filter((plan) => plan.status === 'preserve-user-owned')
            .map((plan) => plan.relativePath),
        timings,
    };
}
function normalizeConfiguredComponents(components) {
    if (Array.isArray(components)) {
        return components;
    }
    if (!components) {
        return [];
    }
    return Object.entries(components).map(([fallbackId, component]) => ({
        ...component,
        id: component.id ?? fallbackId,
    }));
}
function normalizeConfiguredResources(resources) {
    if (Array.isArray(resources)) {
        return resources;
    }
    if (!resources) {
        return [];
    }
    return Object.entries(resources).map(([fallbackId, resource]) => ({
        ...resource,
        id: resource.id ?? fallbackId,
    }));
}
function buildGeneratedArtifacts(map) {
    return [
        {
            relativePath: '.archpilot/reports/architecture-map.json',
            kind: 'json',
            content: (0, architectureMapReporter_1.renderArchitectureMapJson)(map),
        },
        {
            relativePath: '.archpilot/reports/dependency-graph.json',
            kind: 'json',
            content: (0, architectureMapReporter_1.renderDependencyGraphJson)(map),
        },
        {
            relativePath: '.archpilot/reports/architecture-map.md',
            kind: 'markdown',
            content: (0, architectureMapReporter_1.renderArchitectureMapMarkdown)(map),
        },
        {
            relativePath: '.archpilot/reports/module-boundaries.md',
            kind: 'markdown',
            content: (0, architectureMapReporter_1.renderModuleBoundariesMarkdown)(map),
        },
    ];
}
//# sourceMappingURL=setupRefresh.js.map