import os
from pathlib import Path

from ssb_pubmd.adapters.storage import LocalFileStorage
from ssb_pubmd.adapters.storage import Storage
from ssb_pubmd.core.document_publisher import ARTICLE_KEY
from ssb_pubmd.models import Factbox
from ssb_pubmd.models import Highchart


class CreateComponentError(Exception): ...


__all__ = ["Factbox", "Highchart", "create"]


def create(
    key: str,
    data: Factbox | Highchart,
) -> None:
    """Creates a component and prints a Markdown snippet to place in the article text.

    Args:
        key: A unique key for the component.
        data: An SSB component object.

    Raises:
        CreateComponentError: If reserved key is used.
    """
    if key == ARTICLE_KEY:
        raise CreateComponentError(f"Key '{ARTICLE_KEY}' is reserved.")

    if storage_file := os.environ.get("SSB_PUBMD_TEMPORARY_STORAGE"):
        storage: Storage = LocalFileStorage(Path(storage_file))
        storage.update(key, data.model_dump(exclude_none=True))

    div_config = f"{{ #{key} .ssb }}"
    div_content = ""
    if isinstance(data, Factbox):
        div_content = "\nThe factbox content is written here using Markdown syntax.\n\n"

    markdown = f"::: {div_config}\n{div_content}:::"

    print(markdown)
