"""Tests for export.py — eval bundle export logic.

Covers:
    - generate_run_id() format
    - export_eval_bundle() directory layout
    - Run ID filtering
    - Missing trials dir handling
"""

from __future__ import annotations

import json
from pathlib import Path

from clawbench.export import export_eval_bundle, generate_run_id


class TestGenerateRunId:
    """Test generate_run_id() output format."""

    def test_format_has_timestamp_and_hash(self):
        rid = generate_run_id(Path("/skill.md"), "claude-code", "test/model", "docker")
        parts = rid.split("-")
        # Format: YYYYMMDD-HHMMSS-hash8
        assert len(parts) == 3
        assert len(parts[0]) == 8  # date
        assert len(parts[1]) == 6  # time
        assert len(parts[2]) == 8  # hash

    def test_none_skill_path(self):
        rid = generate_run_id(None, "claude-code", "test/model", "docker")
        assert len(rid) > 0

    def test_different_inputs_different_hashes(self):
        rid1 = generate_run_id(Path("/a.md"), "agent1", "model1", "docker")
        rid2 = generate_run_id(Path("/b.md"), "agent2", "model2", "docker")
        # Same timestamp (run in same second) but different hash suffix
        assert rid1.split("-")[2] != rid2.split("-")[2]


class TestExportEvalBundle:
    """Test export_eval_bundle() directory layout."""

    RUN_ID = "20260324-120000-abcd1234"

    def _make_trial(self, trials_dir, name, task_name, run_id=None, files=None):
        trial = trials_dir / name
        trial.mkdir(parents=True, exist_ok=True)
        (trial / "task_name.txt").write_text(task_name + "\n")
        if run_id:
            (trial / "run_id.txt").write_text(run_id + "\n")
        for rel_path, content in (files or {}).items():
            p = trial / rel_path
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_text(content)

    def test_creates_results_json(self, tmp_path):
        trials_dir = tmp_path / "trials"
        trials_dir.mkdir()
        export_dir = tmp_path / "export"

        result_dict = {"skill": "test.md", "summary": {"total": 0}}
        export_eval_bundle(export_dir, result_dict, trials_dir, self.RUN_ID)

        data = json.loads((export_dir / "results.json").read_text())
        assert data["skill"] == "test.md"

    def test_copies_trial_artifacts(self, tmp_path):
        trials_dir = tmp_path / "trials"
        self._make_trial(trials_dir, "t1", "task-a", run_id=self.RUN_ID, files={
            "agent/trajectory.json": '{"steps": []}',
            "verifier/reward.json": '{"score": 1.0}',
            "timing.json": '{"total": 5.0}',
        })

        export_dir = tmp_path / "export"
        export_eval_bundle(export_dir, {"summary": {}}, trials_dir, self.RUN_ID)

        run_dir = export_dir / "trials" / "task-a" / "run-1"
        assert (run_dir / "trajectory.json").exists()
        assert (run_dir / "reward.json").exists()
        assert (run_dir / "timing.json").exists()

    def test_filters_by_run_id(self, tmp_path):
        trials_dir = tmp_path / "trials"
        self._make_trial(trials_dir, "t_old", "old-task", run_id="other-id", files={
            "timing.json": "{}",
        })
        self._make_trial(trials_dir, "t_new", "new-task", run_id=self.RUN_ID, files={
            "timing.json": "{}",
        })

        export_dir = tmp_path / "export"
        export_eval_bundle(export_dir, {"summary": {}}, trials_dir, self.RUN_ID)

        assert (export_dir / "trials" / "new-task" / "run-1").exists()
        assert not (export_dir / "trials" / "old-task").exists()

    def test_nonexistent_trials_dir(self, tmp_path):
        export_dir = tmp_path / "export"
        export_eval_bundle(export_dir, {"summary": {}}, tmp_path / "no-trials", self.RUN_ID)

        assert (export_dir / "results.json").exists()
        assert not (export_dir / "trials").exists()

    def test_renames_existing_export_dir(self, tmp_path):
        trials_dir = tmp_path / "trials"
        trials_dir.mkdir()
        export_dir = tmp_path / "export"
        export_dir.mkdir()
        (export_dir / "marker.txt").write_text("old")

        export_eval_bundle(export_dir, {"summary": {}}, trials_dir, self.RUN_ID)

        assert (export_dir / "results.json").exists()
        assert not (export_dir / "marker.txt").exists()
        renamed = [p for p in tmp_path.iterdir() if p.name.startswith("export.")]
        assert len(renamed) == 1
