"use strict";
/**
 * 🔗 Mirror Engine - The Orchestrator
 * Coordinates all C-Mirror operations
 *
 * This is the main engine that:
 * - Detects which files need syncing
 * - Calls the transformation functions
 * - Uses atomic writes for safety
 * - Emits events for broadcasting
 * - Ensures zero slippage
 *
 * Usage:
 *   const engine = new MirrorEngine(config);
 *   const result = await engine.sync();
 */
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.MirrorEngine = void 0;
const yaml_1 = require("../../../fix-once/yaml");
const faf_to_claude_1 = require("./faf-to-claude");
const claude_to_faf_1 = require("./claude-to-faf");
const atomic_write_1 = require("../strategies/atomic-write");
const event_emitter_1 = require("./events/event-emitter");
const mirror_events_1 = require("./events/mirror-events");
class MirrorEngine {
    config;
    projectPath;
    constructor(config) {
        this.config = {
            atomicWrites: true, // Default to safe writes
            selfHealing: true, // Default to auto-recovery
            ...config
        };
        this.projectPath = config.projectPath || process.cwd();
    }
    /**
     * Main sync operation
     * Intelligently syncs .faf ↔ CLAUDE.md
     */
    async sync() {
        const startTime = Date.now();
        const result = {
            success: false,
            direction: 'none',
            filesChanged: [],
            conflicts: [],
            duration: 0,
            integrity: 'perfect'
        };
        try {
            // Step 1: Analyze file states
            const analysis = await this.analyzeFiles();
            // Step 2: Determine sync strategy
            const strategy = this.determineSyncStrategy(analysis);
            result.direction = strategy;
            // Step 3: Execute sync based on strategy
            if (strategy === 'none') {
                // No sync needed
                result.success = true;
                result.duration = Date.now() - startTime;
                return result;
            }
            if (strategy === 'faf-to-claude') {
                await this.syncFafToClaude(analysis);
                result.filesChanged.push(this.config.readableFile);
            }
            else if (strategy === 'claude-to-faf') {
                await this.syncClaudeToFaf(analysis);
                result.filesChanged.push(this.config.structuredFile);
            }
            else if (strategy === 'bidirectional') {
                // Both files changed - attempt intelligent merge
                // For now, faf wins (can be enhanced later)
                await this.syncFafToClaude(analysis);
                result.filesChanged.push(this.config.readableFile);
                result.conflicts.push('Both files modified - .faf took precedence');
            }
            // Step 4: Verify integrity
            const integrityCheck = await this.verifyIntegrity();
            result.integrity = integrityCheck.status;
            // Step 5: Success
            result.success = true;
            result.duration = Date.now() - startTime;
            // EMIT: Score update (if available)
            if (integrityCheck.score) {
                event_emitter_1.mirrorEvents.emitMirrorEvent((0, mirror_events_1.createMirrorEvent)(mirror_events_1.MirrorEventType.SCORE_UPDATE, {
                    score: integrityCheck.score
                }, {
                    projectPath: this.projectPath,
                    score: integrityCheck.score,
                    duration: result.duration
                }));
            }
            return result;
        }
        catch (error) {
            result.success = false;
            result.error = error instanceof Error ? error.message : String(error);
            result.duration = Date.now() - startTime;
            result.integrity = 'failed';
            return result;
        }
    }
    /**
     * Analyze file states to determine what needs syncing
     */
    async analyzeFiles() {
        const fafPath = this.config.structuredFile;
        const claudePath = this.config.readableFile;
        const fafExists = await (0, atomic_write_1.fileExists)(fafPath);
        const claudeExists = await (0, atomic_write_1.fileExists)(claudePath);
        const fafModified = fafExists ? await (0, atomic_write_1.getFileModifiedTime)(fafPath) : null;
        const claudeModified = claudeExists ? await (0, atomic_write_1.getFileModifiedTime)(claudePath) : null;
        const fafState = {
            path: fafPath,
            exists: fafExists,
            modified: fafModified || undefined
        };
        const claudeState = {
            path: claudePath,
            exists: claudeExists,
            modified: claudeModified || undefined
        };
        return { fafState, claudeState };
    }
    /**
     * Determine sync strategy based on file states
     */
    determineSyncStrategy(analysis) {
        const { fafState, claudeState } = analysis;
        // If neither exists, nothing to sync
        if (!fafState.exists && !claudeState.exists) {
            return 'none';
        }
        // If only .faf exists, create CLAUDE.md
        if (fafState.exists && !claudeState.exists) {
            return 'faf-to-claude';
        }
        // If only CLAUDE.md exists, create .faf (unusual but handle it)
        if (!fafState.exists && claudeState.exists) {
            return 'claude-to-faf';
        }
        // Both exist - check modification times
        if (fafState.modified && claudeState.modified) {
            const fafTime = fafState.modified.getTime();
            const claudeTime = claudeState.modified.getTime();
            // If .faf is newer, sync to CLAUDE.md
            if (fafTime > claudeTime) {
                return 'faf-to-claude';
            }
            // If CLAUDE.md is newer, sync to .faf
            if (claudeTime > fafTime) {
                return 'claude-to-faf';
            }
            // If same time, no sync needed
            return 'none';
        }
        // Default: faf to claude
        return 'faf-to-claude';
    }
    /**
     * Sync .faf → CLAUDE.md
     */
    async syncFafToClaude(analysis) {
        const fafContent = await (0, atomic_write_1.safeRead)(this.config.structuredFile, this.projectPath);
        const claudeMdContent = await (0, faf_to_claude_1.fafToClaudeMd)(fafContent, this.projectPath);
        if (this.config.atomicWrites) {
            await (0, atomic_write_1.atomicWrite)(this.config.readableFile, claudeMdContent, this.projectPath);
        }
        else {
            // Direct write (not recommended)
            const fs = await Promise.resolve().then(() => __importStar(require('fs/promises')));
            await fs.writeFile(this.config.readableFile, claudeMdContent, 'utf-8');
        }
    }
    /**
     * Sync CLAUDE.md → .faf
     */
    async syncClaudeToFaf(analysis) {
        const claudeContent = await (0, atomic_write_1.safeRead)(this.config.readableFile, this.projectPath);
        // Load existing .faf data (or create minimal structure)
        let existingFafData = {};
        if (analysis.fafState.exists) {
            const fafContent = await (0, atomic_write_1.safeRead)(this.config.structuredFile, this.projectPath);
            existingFafData = (0, yaml_1.parse)(fafContent);
        }
        const updatedFafContent = await (0, claude_to_faf_1.claudeMdToFaf)(claudeContent, existingFafData, this.projectPath);
        if (this.config.atomicWrites) {
            await (0, atomic_write_1.atomicWrite)(this.config.structuredFile, updatedFafContent, this.projectPath);
        }
        else {
            // Direct write (not recommended)
            const fs = await Promise.resolve().then(() => __importStar(require('fs/promises')));
            await fs.writeFile(this.config.structuredFile, updatedFafContent, 'utf-8');
        }
    }
    /**
     * Verify integrity after sync
     * Ensures mirror is perfect
     */
    async verifyIntegrity() {
        try {
            // Check both files exist
            const fafExists = await (0, atomic_write_1.fileExists)(this.config.structuredFile);
            const claudeExists = await (0, atomic_write_1.fileExists)(this.config.readableFile);
            if (!fafExists || !claudeExists) {
                return { status: 'failed' };
            }
            // Parse .faf to get score
            const fafContent = await (0, atomic_write_1.safeRead)(this.config.structuredFile, this.projectPath);
            const parsedData = (0, yaml_1.parse)(fafContent);
            const fafData = (!parsedData || typeof parsedData !== 'object') ? {} : parsedData;
            const score = fafData.ai_score !== undefined && fafData.human_score !== undefined ? {
                ai: fafData.ai_score,
                human: fafData.human_score,
                total: fafData.faf_score ? parseInt(fafData.faf_score) : fafData.ai_score + fafData.human_score
            } : undefined;
            // Basic validation passed
            event_emitter_1.mirrorEvents.emitMirrorEvent((0, mirror_events_1.createMirrorEvent)(mirror_events_1.MirrorEventType.INTEGRITY_PERFECT, {
                message: 'Mirror integrity verified'
            }, {
                projectPath: this.projectPath,
                integrity: 'perfect',
                score
            }));
            return { status: 'perfect', score };
        }
        catch (error) {
            event_emitter_1.mirrorEvents.emitMirrorEvent((0, mirror_events_1.createMirrorEvent)(mirror_events_1.MirrorEventType.INTEGRITY_FAILED, {
                error: error instanceof Error ? error.message : String(error)
            }, {
                projectPath: this.projectPath,
                integrity: 'failed'
            }));
            return { status: 'failed' };
        }
    }
}
exports.MirrorEngine = MirrorEngine;
//# sourceMappingURL=mirror-engine.js.map