from typing import List

from .base import BaseEntity, BaseRepository
from ..utils.utils import make_request


class AgentSession(BaseEntity):
    def __init__(
        self,
        id: str = None,
        agent_id: str = None,
        agent_environment_id: str = None,
        deployment_id: str = None,
        status: str = None,
        direction: str = None,
        origin: str = None,
        usage: dict = None,
        tags: list = None,
        telephony_id: str = None,
        telephony_call_id: str = None,
        analytics_processed: bool = None,
        created_at: str = None,
        updated_at: str = None,
        deleted_at: str = None,
        **kwargs,
    ):
        self.id = id
        self.agent_id = agent_id
        self.agent_environment_id = agent_environment_id
        self.deployment_id = deployment_id
        self.status = status
        self.direction = direction
        self.origin = origin
        self.usage = usage
        self.tags = tags
        self.telephony_id = telephony_id
        self.telephony_call_id = telephony_call_id
        self.analytics_processed = analytics_processed
        self.created_at = created_at
        self.updated_at = updated_at
        self.deleted_at = deleted_at


class AgentSessionRepository(BaseRepository[AgentSession]):
    def __init__(self, agent_id: str):
        self.agent_id = agent_id
        super().__init__("session", f"/v1/agents/{agent_id}/sessions", AgentSession)

    def get(self, query: dict | None = None, page: int = None, limit: int = None) -> List[AgentSession]:
        query = query or {}
        parts = []
        for key, value in query.items():
            if value is not None:
                parts.append(f"filters[{key}]={value}")
        if page is not None:
            parts.append(f"page={page}")
        if limit is not None:
            parts.append(f"limit={limit}")
        query_string = "&".join(parts)
        response = make_request(f"{self.endpoint}?{query_string}")

        if response and "data" in response:
            if isinstance(response["data"], list):
                return [self._create_entity(item) for item in response["data"]]
            else:
                return [self._create_entity(response["data"])]
        return []

    def get_trace(self, session_id: str) -> dict | None:
        response = make_request(f"{self.endpoint}/{session_id}/trace")
        if response and "data" in response:
            return response["data"]
        return None

    def get_span(self, session_id: str, span_id: str) -> dict | None:
        response = make_request(f"{self.endpoint}/{session_id}/span/{span_id}")
        if response and "data" in response:
            return response["data"]
        return None

    def get_transcript(self, session_id: str) -> list | None:
        response = make_request(f"/v1/sessions/{session_id}/formatted-events?format=json&filter=transcript")
        if response and "events" in response:
            return response["events"]
        return None

    def get_events(self, session_id: str, page: int = None, limit: int = None) -> dict | None:
        parts = []
        if page is not None:
            parts.append(f"page={page}")
        if limit is not None:
            parts.append(f"limit={limit}")
        query_string = f"?{'&'.join(parts)}" if parts else ""
        response = make_request(f"/v1/sessions/{session_id}/events{query_string}")
        if response and "data" in response:
            return response
        return None
