"""Reconstruct linear conversation from UUID-linked message tree."""

from __future__ import annotations

import logging
from typing import Any

logger = logging.getLogger(__name__)

# Types that form the actual conversation (not internal bookkeeping)
_CONVERSATION_TYPES = {"user", "assistant", "system"}


def linearize_conversation(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Build a linear conversation sequence from messages.

    CC's JSONL has a complex tree structure where streaming chunks, tool results,
    and next turns all branch from different points. Instead of trying to walk the
    tree (which is fragile), we filter to main-thread conversation messages and
    sort by timestamp, which gives the correct chronological order.
    """
    conversation: list[dict[str, Any]] = []

    for msg in messages:
        msg_type = msg.get("type", "")

        # Skip non-conversation types entirely
        if msg_type not in _CONVERSATION_TYPES:
            continue

        # Skip sidechains (subagent messages)
        if msg.get("isSidechain", False):
            continue

        conversation.append(msg)

    # Sort by timestamp (ISO-8601 strings sort correctly)
    conversation.sort(key=lambda m: m.get("timestamp", ""))

    return conversation
