use anyhow::Result;
use microformats::parse;
use microformats::types::Document;
use url::Url;

#[cfg(feature = "debug_flow")]
use microformats::types::DebugDocument;

pub struct ExtendedParser {
    html: String,
}

impl ExtendedParser {
    pub fn from_html(html: String) -> Result<Self> {
        Ok(Self { html })
    }

    /// Parse with source tracking.
    ///
    /// Returns:
    /// - The parsed Document
    /// - Source map mapping value paths to element IDs
    /// - HTML with data-mf2-id markers
    pub fn into_document_with_tracking(
        self,
        base_url: Option<Url>,
    ) -> Result<(
        Document,
        std::collections::HashMap<String, Vec<String>>,
        String,
    )> {
        #[cfg(feature = "debug_flow")]
        {
            // Parse with ID generation for debug tracking
            let mut parser = parse::Parser::from_html(self.html.clone())?.with_id_generation(true);

            let doc = parser.into_document(base_url)?;

            // Convert to debug document
            if let Some(debug_doc) = doc.into_debug_document() {
                // Build source map from debug info
                let mut source_map = std::collections::HashMap::new();

                for (item_idx, item_debug) in debug_doc.value_sources.items.iter().enumerate() {
                    let item_path = format!("items[{}]", item_idx);
                    let mut element_ids = Vec::new();

                    // Add element that created this item
                    if let Some(id) = &item_debug.element.mf2_id {
                        element_ids.push(id.clone());
                    }

                    // Add elements for each property
                    for (_prop_name, prop_sources) in &item_debug.properties {
                        for prop_source in prop_sources {
                            if let Some(id) = &prop_source.element.mf2_id {
                                element_ids.push(id.clone());
                            }
                        }
                    }

                    source_map.insert(item_path, element_ids);
                }

                // Add relations to source map
                for (url, _relation_debug) in &debug_doc.value_sources.relations {
                    // Relations would need element tracking during parsing
                    source_map.insert(format!("rel-urls.{}", url), vec![]);
                }

                Ok((debug_doc.document, source_map, debug_doc.annotated_html))
            } else {
                // Fallback: parse without debug info
                let base_parser = parse::Parser::from_html(self.html.clone())?;
                let doc = base_parser.into_document(base_url)?;
                let source_map = std::collections::HashMap::new();
                Ok((doc, source_map, self.html))
            }
        }

        #[cfg(not(feature = "debug_flow"))]
        {
            // Fallback: parse normally and return empty source map
            let base_parser = parse::Parser::from_html(self.html.clone())?;
            let doc = base_parser.into_document(base_url)?;
            let source_map = std::collections::HashMap::new();
            Ok((doc, source_map, self.html))
        }
    }
}
