import json
from pathlib import Path
from typing import Any

import pytest


def user(text: Any, **extra: Any) -> dict[str, Any]:
    return {
        "type": "user",
        "sessionId": "s1",
        "cwd": str(Path.home() / "github.com/me/proj"),
        "timestamp": "2026-06-10T04:30:00Z",
        "message": {"role": "user", "content": text},
        **extra,
    }


def assistant(blocks: list[dict[str, Any]], output_tokens: int = 100) -> dict[str, Any]:
    return {
        "type": "assistant",
        "sessionId": "s1",
        "cwd": str(Path.home() / "github.com/me/proj"),
        "timestamp": "2026-06-10T04:31:00Z",
        "message": {
            "role": "assistant",
            "model": "claude-fable-5",
            "content": blocks,
            "usage": {
                "output_tokens": output_tokens,
                "input_tokens": 10,
                "cache_read_input_tokens": 5000,
            },
        },
    }


RECORDS = [
    user("fix the bug in auth"),
    user("fix the bug in auth"),
    user([{"type": "text", "text": "no, wait — look at the tests first"}]),
    user("please dude look at this [Image #1]"),
    # noise: every one of these is a user-role record that was never typed
    user([{"type": "tool_result", "tool_use_id": "t1", "content": "ok"}]),
    user(
        "<command-message>digest</command-message>\n<command-name>/digest</command-name>"
    ),
    user("<bash-input>pwd</bash-input>"),
    user("<task-notification>done</task-notification>"),
    user("[Request interrupted by user]"),
    user("a meta message", isMeta=True),
    user("subagent chatter", isSidechain=True),
    assistant([{"type": "tool_use", "name": "Bash", "input": {}}]),
    assistant(
        [
            {"type": "tool_use", "name": "Edit", "input": {}},
            {
                "type": "text",
                "text": "You're absolutely right — the bug in the auth is fixed now.",
            },
        ]
    ),
    {"type": "ai-title", "sessionId": "s1", "aiTitle": "fixing auth"},
    {
        "type": "pr-link",
        "sessionId": "s1",
        "prUrl": "https://github.com/me/proj/pull/1",
        "prNumber": 1,
        "prRepository": "me/proj",
    },
]


@pytest.fixture
def claude_dir(tmp_path: Path) -> Path:
    project_dir = tmp_path / "projects" / "-Users-me-github-com-me-proj"
    project_dir.mkdir(parents=True)
    transcript = project_dir / "s1.jsonl"
    transcript.write_text("\n".join(json.dumps(r) for r in RECORDS) + "\n")
    # subagent sidechain transcripts live in subdirectories and must be ignored
    sidechain_dir = project_dir / "s1"
    sidechain_dir.mkdir()
    (sidechain_dir / "agent-1.jsonl").write_text(
        json.dumps(user("sidechain file")) + "\n"
    )
    return tmp_path
