# pyright: reportMissingImports=false
"""log_stage appends one JSONL record per call with required schema keys."""
from __future__ import annotations

import json
from pathlib import Path

import pytest

from utils import finish_task_timing_logger as ftl


_REQUIRED_KEYS = {"ts", "task_id", "stage", "status", "duration_ms", "meta"}


@pytest.fixture()
def patched_log_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    log_path = tmp_path / "finish-task-timing.jsonl"
    monkeypatch.setattr(ftl, "_LOG_PATH", log_path)
    return log_path


def test_log_stage_creates_file_and_appends_one_line(patched_log_path: Path) -> None:
    assert not patched_log_path.exists()

    ftl.log_stage("task-X", "INIT", "ok", duration_ms=10, meta={"k": "v"})

    assert patched_log_path.exists()
    lines = patched_log_path.read_text(encoding="utf-8").splitlines()
    assert len(lines) == 1


def test_log_stage_record_has_all_required_keys(patched_log_path: Path) -> None:
    ftl.log_stage("task-X", "INIT", "ok", duration_ms=10, meta={"k": "v"})

    record = json.loads(patched_log_path.read_text(encoding="utf-8").splitlines()[0])
    assert set(record.keys()) == _REQUIRED_KEYS
    assert record["task_id"] == "task-X"
    assert record["stage"] == "INIT"
    assert record["status"] == "ok"
    assert record["duration_ms"] == 10
    assert record["meta"] == {"k": "v"}
    assert isinstance(record["ts"], str) and record["ts"]


def test_log_stage_two_calls_yield_two_lines_append_mode(patched_log_path: Path) -> None:
    ftl.log_stage("task-A", "INIT", "ok", duration_ms=1, meta=None)
    ftl.log_stage("task-A", "FINALIZE", "ok", duration_ms=2, meta={"x": 1})

    lines = patched_log_path.read_text(encoding="utf-8").splitlines()
    assert len(lines) == 2

    rec1 = json.loads(lines[0])
    rec2 = json.loads(lines[1])
    assert rec1["stage"] == "INIT"
    assert rec2["stage"] == "FINALIZE"
    # default meta=None becomes {} per implementation
    assert rec1["meta"] == {}
    assert rec2["meta"] == {"x": 1}


def test_log_stage_meta_none_defaults_to_empty_dict(patched_log_path: Path) -> None:
    ftl.log_stage("task-A", "INIT", "ok")
    record = json.loads(patched_log_path.read_text(encoding="utf-8").splitlines()[0])
    assert record["meta"] == {}
    assert record["duration_ms"] is None
