"use strict";
/**
 * ✏️ Edit Command - Interactive .faf editor
 * Claude Code consistency: Similar to /edit command
 */
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.editCommand = editCommand;
const championship_style_1 = require("../utils/championship-style");
const file_utils_1 = require("../utils/file-utils");
const faf_schema_1 = require("../schema/faf-schema");
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const child_process_1 = require("child_process");
const yaml_1 = require("../fix-once/yaml");
/**
 * Interactive .faf file editor with validation
 */
async function editCommand(options = {}) {
    try {
        const startTime = Date.now();
        console.log(championship_style_1.FAF_COLORS.fafCyan(`${championship_style_1.FAF_ICONS.pencil} Interactive .faf Editor`));
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}${championship_style_1.BRAND_MESSAGES.optimization}`);
        const fafPath = await (0, file_utils_1.findFafFile)();
        if (!fafPath) {
            console.log(`${championship_style_1.FAF_COLORS.fafOrange('└─ ')}No .faf file found. Run ${championship_style_1.FAF_COLORS.fafCyan('faf init')} first.`);
            return;
        }
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}Found: ${path.relative(process.cwd(), fafPath)}`);
        // Create backup before editing
        const backupPath = `${fafPath}.edit-backup`;
        const originalContent = await fs.readFile(fafPath, 'utf-8');
        await fs.writeFile(backupPath, originalContent);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}Backup created: ${path.basename(backupPath)}`);
        if (options.section) {
            await editSection(fafPath, options.section);
        }
        else {
            await openInEditor(fafPath, options.editor);
        }
        // Validate after editing (unless explicitly disabled)
        if (options.validate !== false) {
            console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}Validating changes...`);
            const newContent = await fs.readFile(fafPath, 'utf-8');
            const hasChanges = newContent !== originalContent;
            if (hasChanges) {
                try {
                    const fafData = (0, yaml_1.parse)(newContent);
                    const validation = (0, faf_schema_1.validateSchema)(fafData);
                    if (validation.valid) {
                        console.log(`${championship_style_1.FAF_COLORS.fafGreen('├─ ')}☑️ Validation passed!`);
                        // Clean up backup on successful edit
                        await fs.unlink(backupPath);
                    }
                    else {
                        console.log(`${championship_style_1.FAF_COLORS.fafOrange('├─ ')}⚠️ Validation warnings found`);
                        validation.errors.forEach(error => {
                            console.log(`${championship_style_1.FAF_COLORS.fafCyan('│   ')}• ${error.message}`);
                        });
                    }
                }
                catch {
                    console.log(`${championship_style_1.FAF_COLORS.fafOrange('├─ ')}❌ YAML parse error - restoring backup`);
                    await fs.writeFile(fafPath, originalContent);
                    await fs.unlink(backupPath);
                    console.log(`${championship_style_1.FAF_COLORS.fafCyan('└─ ')}Original content restored`);
                    return;
                }
            }
            else {
                console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}No changes made`);
                await fs.unlink(backupPath);
            }
        }
        const duration = Date.now() - startTime;
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafGreen(`${championship_style_1.FAF_ICONS.trophy} Edit session complete in ${duration}ms!`));
        console.log(`${championship_style_1.FAF_COLORS.fafCyan(`${championship_style_1.FAF_ICONS.magic_wand} Try: `)}faf score${championship_style_1.FAF_COLORS.fafCyan(' - Check your updated score')}`);
    }
    catch (error) {
        console.error(championship_style_1.FAF_COLORS.fafOrange(`${championship_style_1.FAF_ICONS.shield} Edit failed: ${error instanceof Error ? error.message : String(error)}`));
        process.exit(1);
    }
}
/**
 * Open .faf file in user's preferred editor
 */
async function openInEditor(fafPath, editorPreference) {
    const editor = editorPreference || getPreferredEditor();
    console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}Opening in ${editor}...`);
    return new Promise((resolve, reject) => {
        const editorProcess = (0, child_process_1.spawn)(editor, [fafPath], {
            stdio: 'inherit'
        });
        editorProcess.on('close', (code) => {
            if (code === 0) {
                resolve();
            }
            else {
                reject(new Error(`Editor exited with code ${code}`));
            }
        });
        editorProcess.on('error', (error) => {
            reject(new Error(`Failed to open editor: ${error.message}`));
        });
    });
}
/**
 * Edit a specific section interactively
 */
async function editSection(fafPath, sectionName) {
    console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}Editing section: ${sectionName}`);
    const content = await fs.readFile(fafPath, 'utf-8');
    const fafData = (0, yaml_1.parse)(content) || {};
    const availableSections = ['project', 'stack', 'scores', 'ai_instructions', 'preferences', 'state', 'human_context'];
    if (!availableSections.includes(sectionName)) {
        console.log(`${championship_style_1.FAF_COLORS.fafOrange('├─ ')}Unknown section: ${sectionName}`);
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('└─ ')}Available: ${availableSections.join(', ')}`);
        return;
    }
    // Create temporary file with just the section
    const tempDir = os.tmpdir();
    const tempFile = path.join(tempDir, `faf-section-${sectionName}-${Date.now()}.yaml`);
    const sectionData = fafData[sectionName] || {};
    const sectionYaml = (0, yaml_1.stringify)({ [sectionName]: sectionData }, { indent: 2 });
    await fs.writeFile(tempFile, sectionYaml);
    try {
        // Open section in editor
        await openInEditor(tempFile);
        // Read back the edited section
        const editedContent = await fs.readFile(tempFile, 'utf-8');
        const editedData = (0, yaml_1.parse)(editedContent);
        // Merge back into main .faf
        fafData[sectionName] = editedData[sectionName];
        const newFafContent = (0, yaml_1.stringify)(fafData, { indent: 2 });
        await fs.writeFile(fafPath, newFafContent);
        console.log(`${championship_style_1.FAF_COLORS.fafGreen('├─ ')}Section ${sectionName} updated successfully`);
    }
    finally {
        // Clean up temp file
        try {
            await fs.unlink(tempFile);
        }
        catch {
            // Ignore cleanup errors
        }
    }
}
/**
 * Detect user's preferred editor
 */
function getPreferredEditor() {
    // Check environment variables in order of preference
    const editorEnv = process.env.VISUAL || process.env.EDITOR;
    if (editorEnv) {
        return editorEnv;
    }
    // For now, return VS Code as default (most common for .faf files)
    // In a full implementation, we'd check which editors are available
    // Common editors would be: ['code', 'subl', 'atom', 'vim', 'nano', 'emacs']
    return 'code';
}
//# sourceMappingURL=edit.js.map