//! Layer 1: Markup Parser (MDX → AST)

pub mod ast;
pub mod directives;
pub mod markdown;
pub mod mdx;

pub use ast::{MarkupAst, MarkupNode};
pub use directives::AgentDirective;

use crate::error::{Error, Result};

/// Markup parser for .agent.mdx files
pub struct MarkupParser;

impl MarkupParser {
    pub fn new() -> Self {
        Self
    }

    /// Parse MDX content into AST
    pub fn parse(&self, content: &str) -> Result<MarkupAst> {
        let (remaining, directives) = mdx::parse_frontmatter(content)
            .map_err(|e| Error::parse(format!("Failed to parse frontmatter: {}", e), None, None))?;

        let (_, body_nodes) = mdx::parse_template_body(remaining.trim()).map_err(|e| {
            Error::parse(format!("Failed to parse template body: {}", e), None, None)
        })?;

        let mut nodes = Vec::new();

        for directive in directives {
            let node = match directive {
                directives::AgentDirective::Agent(config) => MarkupNode::Agent(config),
                directives::AgentDirective::Input(input) => MarkupNode::Input(input),
                directives::AgentDirective::Import(import) => MarkupNode::Import(import),
                directives::AgentDirective::Shell(shell) => MarkupNode::Shell(shell),
                directives::AgentDirective::If(if_block) => MarkupNode::If(if_block),
                directives::AgentDirective::Validate(validation) => {
                    MarkupNode::Validate(validation)
                }
            };
            nodes.push(node);
        }

        nodes.extend(body_nodes);

        Ok(MarkupAst { nodes })
    }
}

impl Default for MarkupParser {
    fn default() -> Self {
        Self::new()
    }
}
