"""Publish synthesis to Notion under the configured parent (page or database)."""

from __future__ import annotations

from typing import TYPE_CHECKING

from folio_notion.integrations.notion_api import NotionAPIError, create_page_under_parent

if TYPE_CHECKING:
    from folio_notion.pipeline_context import PipelineContext


def run(ctx: PipelineContext) -> None:
    if ctx.skip_notion:
        return

    text = ctx.synthesis_text
    if not text:
        raise RuntimeError("No synthesis text for Notion.")

    export_callout = None
    if ctx.export_file:
        export_callout = f"**Saved locally** · `{ctx.export_file.name}`"

    try:
        page = create_page_under_parent(
            ctx.notion_token,
            ctx.notion_parent_id,
            ctx.run_title,
            text,
            max_retries=ctx.notion_api_max_retries,
            export_callout=export_callout,
        )
    except NotionAPIError as e:
        raise RuntimeError(f"Notion publish failed: {e}") from e

    pid = page.get("id", "").replace("-", "")
    if pid:
        ctx.notion_page_url = f"https://www.notion.so/{pid}"
