import os
import subprocess
import tempfile
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.storage import LocalFileStorage
from ssb_pubmd.core.document_processor import Document
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 render_article(file_path: str, cms_client: CmsClient = cms_client) -> str:
    """Processes and syncs the article using the given Cms client, and returns a URL to the rendered preview."""
    publisher = DocumentPublisher(
        response_storage=LocalFileStorage(Path(file_path).parent / ".ssbno.json"),
        cms_client=cms_client,
    )
    document = Document.from_quarto_markdown(file_path)
    return publisher.sync_document(document)
