package parser

import (
	"bufio"
	"strings"
)

// StripMDCFrontmatter removes YAML frontmatter from .mdc files
// .mdc files have optional YAML frontmatter between --- delimiters
// We only need the markdown content for policy extraction
func StripMDCFrontmatter(content string) string {
	lines := strings.Split(content, "\n")

	// Check if file starts with frontmatter delimiter
	if len(lines) == 0 || strings.TrimSpace(lines[0]) != "---" {
		// No frontmatter, return as-is
		return content
	}

	// Find the closing frontmatter delimiter
	scanner := bufio.NewScanner(strings.NewReader(content))
	inFrontmatter := false
	frontmatterEnded := false
	lineNum := 0

	var markdownLines []string

	for scanner.Scan() {
		line := scanner.Text()
		lineNum++

		// First line is opening ---
		if lineNum == 1 && strings.TrimSpace(line) == "---" {
			inFrontmatter = true
			continue
		}

		// Look for closing ---
		if inFrontmatter && strings.TrimSpace(line) == "---" {
			inFrontmatter = false
			frontmatterEnded = true
			continue
		}

		// Skip frontmatter content
		if inFrontmatter {
			continue
		}

		// After frontmatter ends, collect markdown lines
		if frontmatterEnded || lineNum > 1 {
			markdownLines = append(markdownLines, line)
		}
	}

	return strings.Join(markdownLines, "\n")
}
