import { appendGeneratedMarker, parseCanonicalRuleMarkdown, parseMarkdownFrontmatter, renderCanonicalRuleMarkdown, renderMarkdownWithFrontmatter, } from '../../rules/canonical/index.js';
function parseDescription(value) {
    if (typeof value === 'string' && value.trim() !== '') {
        return value.trim();
    }
    return undefined;
}
function parseGlobs(value) {
    if (Array.isArray(value) &&
        value.length > 0 &&
        value.every((glob) => typeof glob === 'string' && glob.trim() !== '')) {
        return value.map((glob) => glob.trim());
    }
    return undefined;
}
function buildCursorFrontmatter(activation, description, globs) {
    if (activation === 'manual') {
        return null;
    }
    return {
        ...(description !== undefined ? { description } : {}),
        alwaysApply: activation === 'always',
        ...(activation === 'glob' && globs ? { globs } : {}),
    };
}
export function transformCanonicalToCursorRule(canonicalContent, canonicalPath) {
    const rule = parseCanonicalRuleMarkdown(canonicalContent);
    const frontmatter = buildCursorFrontmatter(rule.activation, rule.description, rule.globs);
    return appendGeneratedMarker(renderMarkdownWithFrontmatter(frontmatter, rule.body), canonicalPath);
}
export function parseCursorRuleToCanonical(providerContent) {
    const { frontmatter, body } = parseMarkdownFrontmatter(providerContent);
    if (!frontmatter) {
        return renderCanonicalRuleMarkdown({ activation: 'manual' }, body);
    }
    const description = parseDescription(frontmatter.description);
    const globs = parseGlobs(frontmatter.globs);
    const activation = frontmatter.alwaysApply === true
        ? 'always'
        : globs
            ? 'glob'
            : 'agent-requested';
    return renderCanonicalRuleMarkdown({
        ...(description !== undefined ? { description } : {}),
        ...(globs !== undefined ? { globs } : {}),
        activation,
    }, body);
}
