"""Write synthesis markdown under export_dir."""

from __future__ import annotations

import re
from pathlib import Path
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from folio_notion.pipeline_context import PipelineContext


def _safe_filename(title: str) -> str:
    s = re.sub(r"[^\w\s-]", "", title, flags=re.UNICODE).strip()
    s = re.sub(r"[-\s]+", "-", s)
    return (s or "folio-export")[:120]


def run(ctx: PipelineContext) -> None:
    text = ctx.synthesis_text
    if not text:
        raise RuntimeError("No synthesis text to write.")

    out_dir = Path(ctx.config["export_dir"])
    out_dir.mkdir(parents=True, exist_ok=True)
    name = _safe_filename(ctx.run_title) + ".md"
    path = out_dir / name
    header = f"# {ctx.run_title}\n\n"
    meta = (
        f"<!-- notebooklm_notebook_id: {ctx.notebooklm_notebook_id or ''} -->\n"
        f"<!-- sources: {', '.join(p.name for p in ctx.pdf_paths)} -->\n\n"
    )
    path.write_text(header + meta + text, encoding="utf-8")
    ctx.export_file = path
