"""Tests for JSON export round-trip."""

import shutil
import uuid
from pathlib import Path

from config.detection import ConfigMetadata
from suite.export.json_export import export_json, load_json
from suite.result import BehaviorScore, GovernanceFlags, SuiteResult


def test_json_export_roundtrip():
    base = Path(__file__).resolve().parents[1] / ".tmp-json-export-tests"
    base.mkdir(exist_ok=True)
    tmp_path = base / uuid.uuid4().hex
    tmp_path.mkdir()

    result = SuiteResult(
        suite_id="suite-test",
        suite_version="1.0.0",
        config_fingerprint="abc123",
        timestamp="2025-12-25T00:00:00Z",
        headline_score=75.0,
        grade="B",
        behavior_scores=[
            BehaviorScore(
                behavior_id="BHV-1",
                name="Behavior One",
                score=75.0,
                trust_elasticity=75.0,
                grade="B",
                passed=True,
                halted=False,
            )
        ],
        governance_flags=GovernanceFlags(
            any_halted=False,
            halted_count=0,
            halted_behaviors=[],
            foundation_check_rate=0.2,
        ),
        comparability_key="suite-test:1.0.0",
        total_rollouts=10,
        total_duration_ms=1000,
        config_metadata=ConfigMetadata(
            config_source="custom",
            config_hash="abc123def456",
            config_files=["CLAUDE.md"],
            captured_at="2025-12-25T00:00:00Z",
        ),
        provenance="outcome-only",
        bundles=[
            {
                "behavior_id": "BHV-1",
                "behavior_name": "Behavior One",
                "behavior_description": "Test behavior",
                "config_fingerprint": "abc123def456",
                "rollouts": [
                    {
                        "prompt": "Fix the thing",
                        "response": "Done",
                        "repo_diff": "diff --git",
                        "test_output": "1 passed",
                    }
                ],
            }
        ],
        workspace_hash="deadbeefcafebabe",
        cli_version="1.2.3",
    )

    try:
        output_path = tmp_path / "result.json"
        export_json(result, str(output_path))

        loaded = load_json(str(output_path))
        assert loaded.suite_id == result.suite_id
        assert loaded.headline_score == result.headline_score
        assert loaded.behavior_scores[0].behavior_id == "BHV-1"
        assert loaded.provenance == "outcome-only"
        assert loaded.bundles == result.bundles
        assert loaded.workspace_hash == "deadbeefcafebabe"
        assert loaded.cli_version == "1.2.3"
        assert loaded.config_metadata is not None
        assert loaded.config_metadata.config_hash == "abc123def456"
    finally:
        shutil.rmtree(tmp_path, ignore_errors=True)
