import json
import os
import subprocess

from ssb_pubmd.core.document_processor.models import PandocAst


def quarto_markdown_to_pandoc_ast(
    file_path: str, temporary_storage_filepath: str
) -> PandocAst:
    """Executes the Quarto Markdown notebook in a subprocess and converts to pandoc AST.

    When code cells needs to store data to be available after the execution, it should be stored in the temporary storage file given in the environment variable.
    """
    env = os.environ.copy()
    env["SSB_PUBMD_TEMPORARY_STORAGE"] = temporary_storage_filepath
    try:
        result = subprocess.run(
            [
                "quarto",
                "render",
                file_path,
                "--to",
                "json",
                "-M",
                "include:false",
                "--output",
                "-",
            ],
            env=env,
            text=True,
            capture_output=True,
            check=True,
        )
        return json.loads(result.stdout)  # type: ignore
    except subprocess.CalledProcessError as err:
        message = err.stderr.strip()
        raise RuntimeError(f"Quarto render failed:\n{message}") from err
