from __future__ import annotations

from typing import Any

from backend.bootstrap.config import normalize_date
from backend.features.sentiment.engine import (
    COMPONENT_WEIGHTS,
    apply_sentiment_to_dashboard,
    build_sentiment_history,
    latest_contiguous_history,
)


class SentimentServiceMixin:
    def _enrich_dashboard_sentiment(
        self,
        dashboard: dict[str, Any],
        end_date: str,
    ) -> dict[str, Any]:
        history = self.database.list_snapshot_payloads(end_date, 260)
        return apply_sentiment_to_dashboard(dashboard, history)

    def sentiment_history(self, trade_date: str, limit: int = 20) -> dict[str, Any]:
        normalized_date = normalize_date(trade_date)
        limit = max(10, min(120, int(limit)))
        full_series = build_sentiment_history(
            self.database.list_snapshot_payloads(normalized_date, 240)
        )
        series = latest_contiguous_history(full_series)
        rows = series[-limit:]
        return {
            "trade_date": rows[-1]["trade_date"] if rows else normalized_date,
            "available_days": len(series),
            "stored_days": len(full_series),
            "requested_days": limit,
            "rows": rows,
            "weights": COMPONENT_WEIGHTS,
            "normalization": rows[-1]["normalization"] if rows else "固定锚点",
        }
