"""Twitter/X data provider for social sentiment."""

from typing import Any

from .base import Provider, ProviderData


class TwitterData(ProviderData):
    """Twitter specific data."""

    provider: str = "twitter"
    mention_count_24h: int | None = None
    mention_count_7d: int | None = None
    mention_velocity: float | None = None  # Rate of change
    sentiment_score: float | None = None  # -1 to 1
    bullish_ratio: float | None = None  # 0 to 1
    top_influencers_mentions: int | None = None
    trending_rank: int | None = None


class TwitterProvider(Provider):
    """Twitter/X API provider for social sentiment data."""

    name = "twitter"
    base_url = "https://api.twitter.com/2"
    requires_auth = True

    def _get_auth_headers(self) -> dict[str, str]:
        """Get authentication headers."""
        if self.api_key:
            return {"Authorization": f"Bearer {self.api_key}"}
        return {}

    async def fetch_data(self, symbol: str) -> TwitterData:
        """Fetch Twitter mentions and sentiment for a coin."""
        # Search for recent tweets mentioning the symbol
        # This is a simplified implementation - real implementation
        # would need Twitter API v2 with academic or enterprise access
        # for comprehensive sentiment analysis

        try:
            # Search recent tweets
            query = f"${symbol.upper()} OR #{symbol.lower()} -is:retweet lang:en"
            data = await self.get(
                "/tweets/search/recent",
                params={
                    "query": query,
                    "max_results": 100,
                    "tweet.fields": "created_at,public_metrics",
                },
            )

            tweets = data.get("data", [])
            meta = data.get("meta", {})

            if not tweets:
                return TwitterData(symbol=symbol.upper(), raw_data={})

            # Analyze sentiment (simplified - real implementation would use NLP)
            sentiment = self._analyze_sentiment(tweets)

            return TwitterData(
                symbol=symbol.upper(),
                mention_count_24h=len(tweets),
                mention_velocity=self._calculate_velocity(tweets),
                sentiment_score=sentiment["score"],
                bullish_ratio=sentiment["bullish_ratio"],
                raw_data={"tweet_count": len(tweets), "meta": meta},
            )

        except Exception:
            # Return empty data on error
            return TwitterData(symbol=symbol.upper(), raw_data={})

    def _analyze_sentiment(self, tweets: list[dict]) -> dict[str, float]:
        """Simple sentiment analysis based on keywords."""
        bullish_keywords = [
            "moon", "bullish", "buy", "pump", "rocket", "ath", "breakout",
            "undervalued", "gem", "hodl", "accumulate", "dip",
        ]
        bearish_keywords = [
            "dump", "bearish", "sell", "crash", "scam", "rug", "dead",
            "overvalued", "bubble", "avoid", "warning",
        ]

        bullish_count = 0
        bearish_count = 0

        for tweet in tweets:
            text = tweet.get("text", "").lower()
            for word in bullish_keywords:
                if word in text:
                    bullish_count += 1
                    break
            for word in bearish_keywords:
                if word in text:
                    bearish_count += 1
                    break

        total = bullish_count + bearish_count
        if total == 0:
            return {"score": 0.0, "bullish_ratio": 0.5}

        bullish_ratio = bullish_count / total
        # Convert to -1 to 1 scale
        score = (bullish_ratio - 0.5) * 2

        return {"score": score, "bullish_ratio": bullish_ratio}

    def _calculate_velocity(self, tweets: list[dict]) -> float:
        """Calculate mention velocity (tweets per hour)."""
        if not tweets:
            return 0.0

        # Simplified: assume tweets are from last hour
        # Real implementation would calculate actual time span
        return float(len(tweets))
