"""Tests for cc-logger export pipeline."""

from pathlib import Path

from cc_logger.mapper.trajectory import export_session

FIXTURES = Path(__file__).parent / "fixtures"


def test_e2e_simple_session():
    """Test full export pipeline on a fixture session."""
    result = export_session(FIXTURES / "simple_session.jsonl")

    # Root structure
    assert result["schema_version"] == "ATIF-v1.6"
    assert result["session_id"] == "simple_session"
    assert result["agent"]["name"] == "claude-code"
    assert result["agent"]["version"] == "2.1.49"
    assert result["agent"]["model_name"] == "claude-opus-4-6"

    steps = result["steps"]
    assert len(steps) > 0

    # Sequential step IDs
    for i, step in enumerate(steps):
        assert step["step_id"] == i + 1

    # Valid source values
    for step in steps:
        assert step["source"] in ("user", "agent", "system")

    # Check we have user, agent, and system steps
    sources = {s["source"] for s in steps}
    assert "user" in sources
    assert "agent" in sources
    assert "system" in sources


def test_streaming_reassembly():
    """Multi-line assistant response (same message.id) produces one agent step."""
    result = export_session(FIXTURES / "simple_session.jsonl")
    steps = result["steps"]

    # The 3 assistant lines with msg_1 should produce 1 agent step
    agent_steps = [s for s in steps if s["source"] == "agent"]

    # First agent step should have thinking + text + tool_call
    first_agent = agent_steps[0]
    assert first_agent.get("reasoning_content") is not None
    assert "think about" in first_agent["reasoning_content"]
    assert first_agent.get("message") is not None
    assert "write that for you" in first_agent["message"]
    assert first_agent.get("tool_calls") is not None
    assert len(first_agent["tool_calls"]) == 1
    assert first_agent["tool_calls"][0]["function_name"] == "Write"

    # Should have metrics from the last chunk
    assert first_agent.get("metrics") is not None
    assert first_agent["metrics"]["completion_tokens"] == 50


def test_observations_attached():
    """Tool results are attached as observations on agent steps."""
    result = export_session(FIXTURES / "simple_session.jsonl")
    steps = result["steps"]

    agent_steps = [s for s in steps if s["source"] == "agent"]
    first_agent = agent_steps[0]

    assert first_agent.get("observation") is not None
    results = first_agent["observation"]["results"]
    assert len(results) == 1
    assert results[0]["source_call_id"] == "toolu_1"
    assert "File created successfully" in results[0]["content"]


def test_skipped_types():
    """Progress and file-history-snapshot messages are not in output."""
    result = export_session(FIXTURES / "simple_session.jsonl")
    steps = result["steps"]

    for step in steps:
        assert "progress" not in step.get("message", "").lower() or step["source"] == "system"
        assert "bash_progress" not in str(step)
        assert "file-history-snapshot" not in str(step)


def test_sidechain_excluded():
    """Sidechain messages don't appear in main thread output."""
    result = export_session(FIXTURES / "sidechain_session.jsonl")
    steps = result["steps"]

    # user + agent + gap separator + user = 4 steps (no sidechain)
    assert len(steps) == 4

    messages = [s.get("message", "") for s in steps]
    for msg in messages:
        assert "Subagent" not in str(msg)


def test_system_events():
    """System events like compact_boundary appear as system steps."""
    result = export_session(FIXTURES / "simple_session.jsonl")
    steps = result["steps"]

    system_steps = [s for s in steps if s["source"] == "system"]
    assert len(system_steps) >= 1

    compact_step = system_steps[0]
    assert "compact" in compact_step["message"].lower()


def test_final_metrics():
    """Final metrics aggregate per-step token counts."""
    result = export_session(FIXTURES / "simple_session.jsonl")
    fm = result.get("final_metrics", {})

    assert fm.get("total_steps") is not None
    assert fm["total_steps"] > 0
    assert fm.get("total_prompt_tokens") is not None
    assert fm.get("total_completion_tokens") is not None
