import { future } from "fp-future";
import { MarkdownParser } from "./markdown.mjs";
import duckdb from "duckdb";
export async function parse(content) {
    const p = new MarkdownParser();
    const blocks = p.parseMD(content);
    return blocks;
}
export async function execute(blocks) {
    const db = await openDb(":memory:");
    const context = new ExecutionContext(db);
    const results = [];
    try {
        for (const b of blocks) {
            const r = await executeBlock(context, b);
            results.push(r);
        }
    }
    finally {
        await context.close();
    }
    return results;
}
export async function executeBlock(context, block) {
    const f = future();
    const start = Date.now();
    const r = {
        duration: 0,
        original: block,
        representation: null,
    };
    if (block.type == "code") {
        switch (block.language) {
            case "sql": {
                context.db.all(block.code, (err, res) => {
                    if (err)
                        f.reject(err);
                    else {
                        r.representation = res;
                        f.resolve();
                    }
                });
                break;
            }
            default:
                f.resolve();
        }
    }
    else {
        f.resolve();
    }
    await f;
    r.duration = Date.now() - start;
    return r;
}
async function openDb(path) {
    const f = future();
    const db = new duckdb.Database(path, (err, res) => {
        if (err)
            f.reject(err);
        else
            f.resolve(db);
    });
    return f;
}
export class ExecutionContext {
    constructor(db) {
        this.db = db;
    }
    async close() {
        const f = future();
        this.db.close((err, res) => {
            if (err)
                f.reject(err);
            else
                f.resolve(res);
        });
        await f;
    }
}
//# sourceMappingURL=index.mjs.map