"""Tests for export format rendering."""

from bilgeai.cli.commands.export import _render_latex, _render_markdown
from bilgeai.memory.store import RunRecord


def _make_record(**kwargs) -> RunRecord:
    defaults = {
        "run_id": "run_20240101_000000_abc123",
        "timestamp": "2024-01-01T00:00:00",
        "config_hash": "abc123def456",
        "model_name": "meta-llama/Llama-3-8B",
        "status": "completed",
        "config_json": '{"model_name": "meta-llama/Llama-3-8B", "batch_size": 4, "seed": 42}',
        "hardware_json": '{"cpu_cores": 8, "ram_total_gb": 32.0}',
    }
    defaults.update(kwargs)
    return RunRecord(**defaults)


class TestRenderMarkdown:
    def test_basic_output(self):
        record = _make_record()
        md = _render_markdown(record)
        assert "# Training Run" in md
        assert "meta-llama/Llama-3-8B" in md
        assert "| batch_size | 4 |" in md

    def test_with_results(self):
        record = _make_record(best_loss=0.3, final_loss=0.5, total_steps=100)
        md = _render_markdown(record)
        assert "0.3000" in md
        assert "0.5000" in md
        assert "100" in md


class TestRenderLatex:
    def test_basic_output(self):
        record = _make_record()
        tex = _render_latex(record)
        assert "\\begin{table}" in tex
        assert "\\begin{tabular}" in tex
        assert "\\end{table}" in tex
        assert "batch\\_size" in tex  # escaped underscore

    def test_with_results(self):
        record = _make_record(best_loss=0.3, final_loss=0.5)
        tex = _render_latex(record)
        assert "Best Loss" in tex
        assert "0.3000" in tex

    def test_special_chars_escaped(self):
        record = _make_record(config_json='{"model_name": "meta-llama/Llama-3-8B", "note": "100%"}')
        tex = _render_latex(record)
        assert "100\\%" in tex

    def test_no_results_section_when_empty(self):
        record = _make_record()
        tex = _render_latex(record)
        # Should not have results table when no results
        assert tex.count("\\begin{tabular}") == 1
