import subprocess
from pathlib import Path

from ssb_pubmd.adapters.cms_client import CmsClient
from ssb_pubmd.adapters.cms_client import get_cms_client
from ssb_pubmd.adapters.document_processor import PandocDocumentProcessor
from ssb_pubmd.adapters.storage import LocalFileStorage
from ssb_pubmd.core.document_publisher import DocumentPublisher
from ssb_pubmd.environment import cms_environment

cms_client = get_cms_client(cms_environment.base_url, cms_environment.admin_path)


def get_article_preview(file_path: str, cms_client: CmsClient = cms_client) -> str:
    pandoc_document = _quarto_to_pandoc(file_path)
    publisher = DocumentPublisher(
        document_processor=PandocDocumentProcessor(),
        storage=LocalFileStorage(project_folder=Path(file_path).parent),
        cms_client=cms_client,
    )
    return publisher.sync_document(pandoc_document)


def _quarto_to_pandoc(file_path: str) -> str:
    try:
        result = subprocess.run(
            [
                "quarto",
                "render",
                file_path,
                "--to",
                "json",
                "-M",
                "include:false",
                "--output",
                "-",
            ],
            text=True,
            capture_output=True,
            check=True,
        )
        return result.stdout
    except subprocess.CalledProcessError as err:
        message = err.stderr.strip()
        raise RuntimeError(f"Quarto render failed:\n{message}") from err
