use anyhow::Result;

use astmap_core::export::export_markdown;
use astmap_core::ExportStore;

pub fn export_md(
    db: &dyn ExportStore,
    file: Option<&str>,
    token_budget: Option<i64>,
) -> Result<String> {
    let md = export_markdown(db, file, token_budget)?;
    Ok(md)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::infra::discovery::IgnoreWalkDiscovery;
    use astmap_languages::DefaultLanguageRegistry;
    use std::fs;

    fn setup_db(dir: &std::path::Path) -> Box<dyn ExportStore> {
        let db = crate::infra::sqlite::open(dir).unwrap();
        astmap_core::scanner::scan(
            dir,
            db.as_ref(),
            true,
            &DefaultLanguageRegistry,
            &IgnoreWalkDiscovery,
        )
        .unwrap();
        db
    }

    #[test]
    fn export_all() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(src.join("lib.rs"), "pub fn hello() {}\npub fn world() {}").unwrap();

        let db = setup_db(dir.path());
        let md = export_md(db.as_ref(), None, None).unwrap();
        assert!(md.contains("Code Structure Index"));
        assert!(md.contains("hello"));
    }

    #[test]
    fn export_with_file_filter() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(src.join("lib.rs"), "pub fn hello() {}").unwrap();

        let db = setup_db(dir.path());
        let md = export_md(db.as_ref(), Some("lib.rs"), None).unwrap();
        assert!(md.contains("hello") || md.contains("lib.rs"));
    }

    #[test]
    fn export_with_token_budget() {
        let dir = tempfile::tempdir().unwrap();
        let src = dir.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(src.join("lib.rs"), "pub fn hello() {}").unwrap();

        let db = setup_db(dir.path());
        let md = export_md(db.as_ref(), None, Some(50)).unwrap();
        assert!(!md.is_empty());
    }
}
