// tools/detect-drift-event.ts — Event schema drift detection helper (SPEC-031)
// Reads event contracts for a spec and compares against locally stored schemas.
import { readFile, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { projectDataDir } from '../storage/index.js';
import { detectDrift } from '../engine/event-schema-validator.js';
/**
 * Detect event schema drift for all event contracts referenced by a spec.
 * Reads contracts from data/projects/{projectId}/event-contracts/ and
 * compares the stored contract JSON schema against any `_impl.json` sidecar
 * that the implementation layer can write to indicate its actual schema.
 *
 * In practice, for static analysis, we compare the contract against itself
 * (no drift) unless an implementation schema sidecar exists at:
 *   data/projects/{projectId}/event-contracts/{eventName}/{version}_impl.json
 *
 * Returns an empty array when no contracts are found or no drift exists.
 */
export async function detectEventSchemaDrift(projectId, _specId) {
    const contractsDir = join(projectDataDir(projectId), 'event-contracts');
    const drifts = [];
    let eventNames;
    try {
        const entries = await readdir(contractsDir, { withFileTypes: true });
        eventNames = entries.filter((e) => e.isDirectory() && e.name !== 'sagas').map((e) => e.name);
    }
    catch {
        // No event-contracts directory — no drift to report
        return drifts;
    }
    for (const eventName of eventNames) {
        const contract = await loadLatestContract(contractsDir, eventName);
        if (!contract) {
            continue;
        }
        // Look for an implementation schema sidecar
        const implSchemaPath = join(contractsDir, eventName, `${contract.currentVersion}_impl.json`);
        let rawImplSchema;
        try {
            rawImplSchema = await readFile(implSchemaPath, 'utf-8');
        }
        catch {
            // No sidecar — no drift to compute
            continue;
        }
        const implSchema = JSON.parse(rawImplSchema);
        const drift = detectDrift(contract, implSchema);
        if (drift) {
            drifts.push(drift);
        }
    }
    return drifts;
}
async function loadLatestContract(contractsDir, eventName) {
    for (let major = 99; major >= 1; major--) {
        const contractPath = join(contractsDir, eventName, `v${major}.json`);
        try {
            const raw = await readFile(contractPath, 'utf-8');
            return JSON.parse(raw);
        }
        catch {
            continue;
        }
    }
    return null;
}
//# sourceMappingURL=detect-drift-event.js.map