from __future__ import annotations

import json
from pathlib import Path


class TraceMarkdownWriter:
    def initialize(self, path: Path, lines: list[str]) -> None:
        path.write_text("\n".join(lines) + "\n", encoding="utf-8")

    def append_section(self, path: Path, title: str, payload: dict | list | str) -> None:
        body = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False, indent=2)
        with path.open("a", encoding="utf-8") as handle:
            handle.write(f"\n## {title}\n")
            if isinstance(payload, str):
                handle.write(body + "\n")
            else:
                handle.write("```json\n")
                handle.write(body + "\n")
                handle.write("```\n")
