"""
Summary Operations Mixin for ContextStore.

Provides summary version management functionality:
- add_summary_version: Store a new summary version
- get_summary_history: List summary versions
- get_summary_version: Get specific version
- get_latest_summary_version: Get current version number
"""

import uuid
from typing import Dict, List, Optional

from ..utils.timestamps import utc_now_iso


class SummaryMixin:
    """
    Mixin class providing summary management operations.

    Requires the base class to have:
    - self.db: LanceDB connection
    - self.summaries_table: LanceDB table (or None)
    - self.summaries_table_name: str
    - self.project_name: str
    """

    def add_summary_version(self, version_data: dict) -> dict:
        """
        Add a summary version to the history table.

        Args:
            version_data: Summary data dict with keys:
                - project, version, summary, generated_at, memory_count, etc.

        Returns:
            Dict with the created record ID
        """
        summary_id = f"sum_v{version_data.get('version', 0)}_{uuid.uuid4().hex[:8]}"

        record = {
            "id": summary_id,
            "project": version_data.get("project", self.project_name),
            "version": version_data.get("version", 0),
            "summary": version_data.get("summary", ""),
            "previous_summary": version_data.get("previous_summary", ""),
            "generated_at": version_data.get("generated_at", utc_now_iso()),
            "memory_count": version_data.get("memory_count", 0),
            "new_memories_count": version_data.get("new_memories_count", 0),
            "trigger": version_data.get("trigger", "unknown")
        }

        if self.summaries_table is None:
            self.summaries_table = self.db.create_table(self.summaries_table_name, [record])
        else:
            self.summaries_table.add([record])

        print(f"[Store:{self.project_name}] Added summary v{record['version']} to history")
        return {"id": summary_id, "version": record["version"]}

    def get_summary_history(self, limit: int = 50) -> List[dict]:
        """
        Get summary version history.

        Args:
            limit: Maximum number of versions to return

        Returns:
            List of summary records (newest first by version)
        """
        if self.summaries_table is None:
            return []

        try:
            df = self.summaries_table.to_pandas()
            if df.empty:
                return []

            # Sort by version descending (newest first)
            df = df.sort_values(by="version", ascending=False)

            results = []
            for _, r in df.head(limit).iterrows():
                results.append({
                    "id": r.get("id"),
                    "project": r.get("project"),
                    "version": int(r.get("version", 0)),
                    "summary": r.get("summary", ""),
                    "generated_at": r.get("generated_at", ""),
                    "memory_count": int(r.get("memory_count", 0)),
                    "new_memories_count": int(r.get("new_memories_count", 0)),
                    "trigger": r.get("trigger", "")
                })

            return results
        except Exception as e:
            print(f"[Store:{self.project_name}] Error getting summary history: {e}")
            return []

    def get_summary_version(self, version: int) -> Optional[dict]:
        """
        Get a specific summary version from history.

        Args:
            version: Version number to retrieve

        Returns:
            Summary record or None if not found
        """
        if self.summaries_table is None:
            return None

        try:
            df = self.summaries_table.to_pandas()
            match = df[df["version"] == version]

            if match.empty:
                return None

            r = match.iloc[0]
            return {
                "id": r.get("id"),
                "project": r.get("project"),
                "version": int(r.get("version", 0)),
                "summary": r.get("summary", ""),
                "previous_summary": r.get("previous_summary", ""),
                "generated_at": r.get("generated_at", ""),
                "memory_count": int(r.get("memory_count", 0)),
                "new_memories_count": int(r.get("new_memories_count", 0)),
                "trigger": r.get("trigger", "")
            }
        except Exception as e:
            print(f"[Store:{self.project_name}] Error getting summary version {version}: {e}")
            return None

    def get_latest_summary_version(self) -> int:
        """
        Get the latest summary version number.

        Returns:
            Latest version number or 0 if no summaries exist
        """
        if self.summaries_table is None:
            return 0

        try:
            df = self.summaries_table.to_pandas()
            if df.empty:
                return 0
            return int(df["version"].max())
        except Exception:
            return 0
