"""Analyze resource for personality scoring."""

from __future__ import annotations

from typing import TYPE_CHECKING

from ..types.analyze import AnalysisResult, BatchAnalysisItem, BatchAnalysisResult

if TYPE_CHECKING:
    from .._base import AsyncHTTPClient, SyncHTTPClient


class AnalyzeResource:
    """Sync resource for text personality analysis.

    Analyze text to extract personality scores across all 10 dimensions.
    Uses multi-signal ensemble analysis (embeddings, lexical, classifier, syntactic).

    Example:
        ```python
        import lindr

        client = lindr.Client(api_key="lindr_...")

        # Analyze a single text
        result = client.analyze.text("I'm excited to collaborate on this project!")
        print(result.scores.extraversion)  # e.g., 72.5

        # Analyze multiple texts efficiently
        batch_result = client.analyze.batch([
            {"id": "1", "content": "Hello, I'd love to help you!"},
            {"id": "2", "content": "This is unacceptable. Fix it now."},
        ])
        for item in batch_result.results:
            print(f"{item.id}: extraversion={item.scores.extraversion}")
        ```
    """

    def __init__(self, client: SyncHTTPClient):
        self._client = client

    def text(
        self,
        text: str,
        *,
        include_details: bool = False,
    ) -> AnalysisResult:
        """Analyze text and return personality scores.

        Args:
            text: Text content to analyze (1-50000 characters)
            include_details: Include detailed signal breakdown in response

        Returns:
            AnalysisResult with scores, confidence, and method used
        """
        response = self._client.post(
            "/analyze",
            json={
                "text": text,
                "includeDetails": include_details,
            },
        )
        return AnalysisResult.model_validate(response)

    def batch(
        self,
        texts: list[dict[str, str]],
        *,
        include_details: bool = False,
    ) -> BatchAnalysisResult:
        """Analyze multiple texts in a single request.

        More efficient than multiple individual calls for batch processing.

        Args:
            texts: List of dicts with 'id' and 'content' keys (max 100 items)
            include_details: Include detailed signal breakdown in response

        Returns:
            BatchAnalysisResult with results for each text and summary

        Example:
            ```python
            result = client.analyze.batch([
                {"id": "sample_1", "content": "First text to analyze"},
                {"id": "sample_2", "content": "Second text to analyze"},
            ])
            ```
        """
        response = self._client.post(
            "/analyze/batch",
            json={
                "texts": texts,
                "includeDetails": include_details,
            },
        )
        return BatchAnalysisResult.model_validate(response)


class AsyncAnalyzeResource:
    """Async resource for text personality analysis.

    Example:
        ```python
        import asyncio
        import lindr

        async def main():
            async with lindr.AsyncClient(api_key="lindr_...") as client:
                # Analyze texts concurrently
                results = await asyncio.gather(
                    client.analyze.text("Hello!"),
                    client.analyze.text("Goodbye!"),
                )
        ```
    """

    def __init__(self, client: AsyncHTTPClient):
        self._client = client

    async def text(
        self,
        text: str,
        *,
        include_details: bool = False,
    ) -> AnalysisResult:
        """Analyze text and return personality scores.

        Args:
            text: Text content to analyze (1-50000 characters)
            include_details: Include detailed signal breakdown in response

        Returns:
            AnalysisResult with scores, confidence, and method used
        """
        response = await self._client.post(
            "/analyze",
            json={
                "text": text,
                "includeDetails": include_details,
            },
        )
        return AnalysisResult.model_validate(response)

    async def batch(
        self,
        texts: list[dict[str, str]],
        *,
        include_details: bool = False,
    ) -> BatchAnalysisResult:
        """Analyze multiple texts in a single request.

        Args:
            texts: List of dicts with 'id' and 'content' keys (max 100 items)
            include_details: Include detailed signal breakdown in response

        Returns:
            BatchAnalysisResult with results for each text and summary
        """
        response = await self._client.post(
            "/analyze/batch",
            json={
                "texts": texts,
                "includeDetails": include_details,
            },
        )
        return BatchAnalysisResult.model_validate(response)
