// Copyright (c) 2026 Modelware. All rights reserved.

import type { MarkdownFrontMatter } from './md-types.js';
import { parseYamlMap } from './md-yaml.js';

export function stripLeadingFrontMatter(markdown: string): string {
    const normalized = markdown.replace(/^\uFEFF/, '');
    const frontMatter = extractLeadingFrontMatter(normalized);
    if (!frontMatter) {
        return normalized;
    }
    return normalized.slice(frontMatter.raw.length);
}

export function extractLeadingFrontMatter(markdown: string): MarkdownFrontMatter | undefined {
    const normalized = markdown.replace(/^\uFEFF/, '');
    const yamlMatch = /^(---[ \t]*\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$))/.exec(normalized);
    if (yamlMatch) {
        const yamlBody = yamlMatch[1]
            .replace(/^---[ \t]*\r?\n/, '')
            .replace(/\r?\n---[ \t]*(?:\r?\n|$)$/, '');
        const yamlData = parseYamlMap(yamlBody);
        return {
            raw: yamlMatch[1],
            ontology: extractOntologyFromData(yamlData) ?? extractOntology(yamlMatch[1]),
            data: yamlData,
        };
    }
    const tomlMatch = /^(\+\+\+[ \t]*\r?\n[\s\S]*?\r?\n\+\+\+[ \t]*(?:\r?\n|$))/.exec(normalized);
    if (tomlMatch) {
        return {
            raw: tomlMatch[1],
            ontology: extractOntology(tomlMatch[1])
        };
    }
    return undefined;
}

export function extractOntology(frontMatterRaw: string): string | undefined {
    const match = /^ontology\s*:\s*(.+)$/m.exec(frontMatterRaw);
    if (!match) {
        return undefined;
    }
    return match[1].trim().replace(/^['"]|['"]$/g, '');
}

function extractOntologyFromData(data: Record<string, unknown> | undefined): string | undefined {
    if (!data) {
        return undefined;
    }
    const value = typeof data.ontology === 'string' ? data.ontology : undefined;
    return typeof value === 'string' ? value : undefined;
}
