import { minimatch } from "minimatch";
import * as path from "node:path";
import { parseFrontmatter } from "../utils/markdownParser.js";
export class MemoryRuleService {
    /**
     * Parses a markdown file into a MemoryRule object.
     */
    parseRule(content, filePath, source) {
        const { frontmatter, content: bodyContent } = parseFrontmatter(content);
        const metadata = {};
        if (frontmatter) {
            if (Array.isArray(frontmatter.paths)) {
                metadata.paths = frontmatter.paths.filter((p) => typeof p === "string");
            }
            else if (typeof frontmatter.paths === "string") {
                metadata.paths = [frontmatter.paths];
            }
            if (typeof frontmatter.priority === "number") {
                metadata.priority = frontmatter.priority;
            }
            else if (typeof frontmatter.priority === "string") {
                const parsed = parseInt(frontmatter.priority, 10);
                if (!isNaN(parsed)) {
                    metadata.priority = parsed;
                }
            }
        }
        return {
            id: filePath, // Use absolute path as ID for now
            content: bodyContent.trim(),
            metadata,
            source,
            filePath,
        };
    }
    /**
     * Determines if a rule matches any of the given file paths using minimatch.
     */
    isRuleActive(rule, filesInContext, workdir) {
        if (!rule.metadata.paths || rule.metadata.paths.length === 0) {
            return true;
        }
        return filesInContext.some((filePath) => {
            // Normalize path relative to workdir if it's an absolute path
            let normalizedPath = filePath;
            if (workdir && path.isAbsolute(filePath)) {
                normalizedPath = path.relative(workdir, filePath);
            }
            return rule.metadata.paths.some((pattern) => {
                const isMatch = minimatch(normalizedPath, pattern, { dot: true });
                return isMatch;
            });
        });
    }
}
