"use strict";
/**
 * 🔍 Search Command - Search within .faf content
 * Claude Code consistency: Similar to /search 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.searchCommand = searchCommand;
const championship_style_1 = require("../utils/championship-style");
const file_utils_1 = require("../utils/file-utils");
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const yaml_1 = require("../fix-once/yaml");
/**
 * Search within .faf file content with intelligent highlighting
 */
async function searchCommand(query, options = {}) {
    try {
        const startTime = Date.now();
        if (!query) {
            console.log(championship_style_1.FAF_COLORS.fafOrange(`${championship_style_1.FAF_ICONS.magnifying_glass} Search requires a query`));
            console.log(`${championship_style_1.FAF_COLORS.fafCyan('Usage: ')}faf search <query> [options]`);
            return;
        }
        console.log(championship_style_1.FAF_COLORS.fafCyan(`${championship_style_1.FAF_ICONS.magnifying_glass} Searching .faf Content`));
        console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}Query: "${query}"`);
        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('├─ ')}Searching: ${path.relative(process.cwd(), fafPath)}`);
        const content = await fs.readFile(fafPath, 'utf-8');
        const fafData = (0, yaml_1.parse)(content) || {};
        const matches = await searchFafData(fafData, query, options);
        const duration = Date.now() - startTime;
        if (options.count) {
            console.log(`${championship_style_1.FAF_COLORS.fafGreen('└─ ')}Found ${matches.length} matches`);
        }
        else if (matches.length === 0) {
            console.log(`${championship_style_1.FAF_COLORS.fafOrange('└─ ')}No matches found for "${query}"`);
        }
        else {
            console.log(`${championship_style_1.FAF_COLORS.fafCyan('├─ ')}Found ${matches.length} matches:`);
            console.log();
            matches.forEach((match, index) => {
                const connector = index === matches.length - 1 ? '└─' : '├─';
                const highlightedValue = highlightQuery(match.value, query, options.case);
                console.log(`${championship_style_1.FAF_COLORS.fafCyan(`${connector} `)}${championship_style_1.FAF_COLORS.fafGreen(match.path)}`);
                console.log(`${championship_style_1.FAF_COLORS.fafCyan('   ')}${highlightedValue}`);
            });
        }
        console.log();
        console.log(championship_style_1.FAF_COLORS.fafGreen(`${championship_style_1.FAF_ICONS.trophy} Search complete in ${duration}ms!`));
        console.log(`${championship_style_1.FAF_COLORS.fafCyan(`${championship_style_1.FAF_ICONS.magic_wand} Try: `)}faf edit --section <section>${championship_style_1.FAF_COLORS.fafCyan(' - Edit matching section')}`);
    }
    catch (error) {
        console.error(championship_style_1.FAF_COLORS.fafOrange(`${championship_style_1.FAF_ICONS.shield} Search failed: ${error instanceof Error ? error.message : String(error)}`));
        process.exit(1);
    }
}
/**
 * Recursively search through .faf data structure
 */
async function searchFafData(data, query, options) {
    const matches = [];
    const caseSensitive = options.case || false;
    const searchQuery = caseSensitive ? query : query.toLowerCase();
    function searchRecursive(obj, currentPath = '', section = 'root') {
        if (typeof obj === 'object' && obj !== null) {
            for (const [key, value] of Object.entries(obj)) {
                const newPath = currentPath ? `${currentPath}.${key}` : key;
                const newSection = currentPath === '' ? key : section;
                // Search in keys (if not disabled)
                if (!options.values) {
                    const searchKey = caseSensitive ? key : key.toLowerCase();
                    if (searchKey.includes(searchQuery)) {
                        matches.push({
                            path: newPath,
                            key,
                            value: String(value),
                            section: newSection
                        });
                    }
                }
                // Search in values (if not disabled)
                if (!options.keys && typeof value === 'string') {
                    const searchValue = caseSensitive ? value : value.toLowerCase();
                    if (searchValue.includes(searchQuery)) {
                        matches.push({
                            path: newPath,
                            key,
                            value,
                            section: newSection
                        });
                    }
                }
                // Recurse into objects/arrays
                if (typeof value === 'object' && value !== null) {
                    searchRecursive(value, newPath, newSection);
                }
            }
        }
    }
    // If searching specific section, start there
    if (options.section) {
        if (data[options.section]) {
            searchRecursive(data[options.section], options.section, options.section);
        }
        else {
            console.log(`${championship_style_1.FAF_COLORS.fafOrange('├─ ')}Section "${options.section}" not found`);
        }
    }
    else {
        searchRecursive(data);
    }
    return matches;
}
/**
 * Highlight query matches in text
 */
function highlightQuery(text, query, caseSensitive = false) {
    if (!text || !query) {
        return text;
    }
    const searchText = caseSensitive ? text : text.toLowerCase();
    const searchQuery = caseSensitive ? query : query.toLowerCase();
    let result = text;
    let index = searchText.indexOf(searchQuery);
    while (index !== -1) {
        const before = result.substring(0, index);
        const match = result.substring(index, index + query.length);
        const after = result.substring(index + query.length);
        result = before + championship_style_1.FAF_COLORS.fafOrange(match) + after;
        // Find next occurrence (adjust index for added color codes)
        const colorCodeLength = championship_style_1.FAF_COLORS.fafOrange('').length * 2; // Start + end codes
        const newSearchText = result.toLowerCase();
        index = newSearchText.indexOf(searchQuery, index + query.length + colorCodeLength);
    }
    return result;
}
//# sourceMappingURL=search.js.map