import subprocess
from pathlib import Path

from ssb_pubmd.adapters.content_parser import MimirContentParser
from ssb_pubmd.adapters.document_processor import PandocDocumentProcessor
from ssb_pubmd.adapters.publish_client import PublishClient
from ssb_pubmd.adapters.storage import LocalFileStorage
from ssb_pubmd.domain.document_publisher import sync_document


def sync_file(file_path: str, publish_client: PublishClient) -> str:
    pandoc_document = _quarto_to_pandoc(file_path)
    adapters = (
        PandocDocumentProcessor(),
        MimirContentParser(),
        LocalFileStorage(project_folder=Path(file_path).parent),
        publish_client,
    )
    return sync_document(pandoc_document, *adapters)


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() or "Quarto failed with no error output"
        raise RuntimeError(f"Quarto render failed:\n{message}") from err
