from __future__ import annotations

from typing import Any

from src.platform_adapter.base_adapter import BaseAdapter, PlatformContent


class TwitterAdapter(BaseAdapter):
    def get_max_length(self) -> int:
        return 280

    def format_content(self, content: str, **kwargs: Any) -> PlatformContent:
        if kwargs.get("format") == "thread":
            return self._create_thread(content)
        truncated = self.truncate_content(content)
        return PlatformContent(title=None, body=truncated, metadata={"platform": "twitter"})

    def _create_thread(self, content: str) -> PlatformContent:
        tweets = []
        sentences = content.replace("\n", " ").split(". ")
        current = ""
        for s in sentences:
            if len(current) + len(s) < 270:
                current += " " + s if current else s
            else:
                if current:
                    tweets.append(current)
                current = s
        if current:
            tweets.append(current)
        numbered = [f"{i+1}/{len(tweets)} {t}" for i, t in enumerate(tweets)]
        return PlatformContent(
            title=None,
            body="\n\n---\n\n".join(numbered),
            metadata={"tweet_count": len(tweets), "is_thread": True},
        )
