// Markdown to HTML Converter - Stress tests string manipulation and parsing
//
// This demonstrates:
// - String parsing and manipulation
// - ADTs for document structure
// - Recursive processing
// - Pattern matching on strings

// Markdown AST
type MarkdownNode =
    | MHeading(Int, String)
    | MParagraph(String)
    | MList(Bool, List<String>)
    | MHorizontalRule

// Parse a line to determine block type
fn parseBlockType(line: String): MarkdownNode =
    if String.startsWith(line, "# ") then
        MHeading(1, String.substring(line, 2, String.length(line)))
    else if String.startsWith(line, "## ") then
        MHeading(2, String.substring(line, 3, String.length(line)))
    else if String.startsWith(line, "### ") then
        MHeading(3, String.substring(line, 4, String.length(line)))
    else if String.startsWith(line, "---") then
        MHorizontalRule
    else if String.startsWith(line, "- ") then
        MList(false, [String.substring(line, 2, String.length(line))])
    else
        MParagraph(line)

// Convert to HTML
fn nodeToHtml(node: MarkdownNode): String =
    match node {
        MHeading(level, text) => "<h" + toString(level) + ">" + text + "</h" + toString(level) + ">",
        MParagraph(text) => if text == "" then "" else "<p>" + text + "</p>",
        MList(ordered, items) => {
            let tag = if ordered then "ol" else "ul"
            let itemsHtml = List.map(items, fn(item: String): String => "<li>" + item + "</li>")
            "<" + tag + ">" + String.join(itemsHtml, "") + "</" + tag + ">"
        },
        MHorizontalRule => "<hr />"
    }

// Convert markdown string to HTML
fn convert(markdown: String): String = {
    let lines = String.lines(markdown)
    let nodes = List.map(lines, parseBlockType)
    let htmlLines = List.filter(List.map(nodes, nodeToHtml), fn(s: String): Bool => s != "")
    String.join(htmlLines, "\n")
}

// Test the converter
fn main(): Unit with {Console} = {
    Console.print("========================================")
    Console.print("     MARKDOWN TO HTML CONVERTER")
    Console.print("========================================")
    Console.print("")

    Console.print("Test 1: Headings")
    Console.print(convert("# Heading 1"))
    Console.print(convert("## Heading 2"))
    Console.print(convert("### Heading 3"))
    Console.print("")

    Console.print("Test 2: Paragraphs")
    Console.print(convert("This is a paragraph."))
    Console.print(convert("Another paragraph here."))
    Console.print("")

    Console.print("Test 3: Lists")
    Console.print(convert("- Item 1"))
    Console.print(convert("- Item 2"))
    Console.print("")

    Console.print("Test 4: Horizontal rule")
    Console.print(convert("---"))
}

let output = run main() with {}
