from __future__ import annotations

import json
from datetime import datetime
from pathlib import Path


class ArtifactWriter:
    def __init__(self, artifacts_dir: Path, test_name: str, run_started_at: datetime) -> None:
        self._artifacts_dir = artifacts_dir
        self._test_name = test_name
        self._run_started_at = run_started_at

    @property
    def path(self) -> Path:
        stamp = self._run_started_at.strftime("%Y%m%d_%H%M%S")
        name = f"{self._test_name}_{stamp}.jsonl"
        return self._artifacts_dir / name

    def write_record(self, payload: dict) -> None:
        self.path.parent.mkdir(parents=True, exist_ok=True)
        with self.path.open("a", encoding="utf-8") as handle:
            handle.write(json.dumps(payload, ensure_ascii=False) + "\n")
