from __future__ import annotations

import uuid
from dataclasses import dataclass, field

from leshy.core.models import AttackPayload, TargetResponse


@dataclass
class Turn:
    """A single turn in a multi-turn conversation."""

    payload: AttackPayload
    response: TargetResponse


@dataclass
class SessionContext:
    """Tracks multi-turn conversation state."""

    thread_id: str = field(default_factory=lambda: uuid.uuid4().hex)
    turns: list[Turn] = field(default_factory=list)

    @property
    def turn_count(self) -> int:
        return len(self.turns)

    def add_turn(self, payload: AttackPayload, response: TargetResponse) -> None:
        self.turns.append(Turn(payload=payload, response=response))

    @property
    def history(self) -> list[dict[str, str]]:
        """Return conversation history as a list of role/content dicts."""
        result: list[dict[str, str]] = []
        for turn in self.turns:
            result.append({"role": "user", "content": turn.payload.content})
            result.append({"role": "assistant", "content": turn.response.content})
        return result
