"""
Activation Store — tracks the user's activation journey.

State machine:
  installed → first_task_started → first_task_complete
            → second_task_started → second_task_complete (optimization detected)
            → activated (full value demonstrated)

Generates InsightCards on task completion:
  - Task 1 complete → "🧠 Memory Created"
  - Task 2+ with workflow reuse → "⚡ Optimization Detected"
"""

import time
import threading
from typing import Dict, Any, List, Optional


class ActivationStore:
    def __init__(self):
        self._lock = threading.Lock()
        self._installed_at = int(time.time())
        self._task_count = 0
        self._total_stored = 0
        self._total_reused = 0
        self._total_steps_skipped = 0
        self._insight_cards: List[Dict[str, Any]] = []
        self._reuse_events: List[Dict[str, Any]] = []
        self._activation_state = "installed"  # installed | first_task | activated

    # ─── Hooks ─────────────────────────────────────────────────────────────

    def on_install(self) -> Dict[str, Any]:
        """Called once on adapter init. Returns activation panel payload."""
        return self.get_activation_panel()

    def on_task_start(self, task_id: str = "", query: str = "") -> Optional[Dict[str, Any]]:
        """Returns Guided First Task card if this is the first task."""
        with self._lock:
            if self._task_count == 0:
                return {
                    "type": "guided_first_task",
                    "title": "Try your first task",
                    "body": query or "Deploy a backend service",
                    "hint": "Run it twice to see the difference.",
                }
        return None

    def on_task_complete(
        self,
        summary: str,
        memories_stored: int = 0,
        workflows_reused: int = 0,
        steps_skipped: int = 0,
        task_id: str = "",
    ) -> Dict[str, Any]:
        """
        Called after each task. Returns an InsightCard for the UI.
        """
        with self._lock:
            self._task_count += 1
            self._total_stored += memories_stored
            self._total_reused += workflows_reused
            self._total_steps_skipped += steps_skipped

            if self._task_count == 1:
                self._activation_state = "first_task"
                card = self._card_memory_created(memories_stored, summary, task_id)
            elif workflows_reused > 0:
                self._activation_state = "activated"
                card = self._card_optimization_detected(
                    workflows_reused, steps_skipped, summary, task_id
                )
            else:
                card = self._card_memory_updated(memories_stored, summary, task_id)

            self._insight_cards.append(card)
            return card

    def on_workflow_adopted(self, workflow_summary: str = "", task_id: str = "") -> Dict[str, Any]:
        """Called when a workflow is reused. Returns Reuse Indicator payload."""
        event = {
            "type": "reuse_indicator",
            "title": "⚡ Reusing past experience",
            "body": workflow_summary or "A previously successful workflow is being applied.",
            "task_id": task_id,
            "ts": int(time.time()),
        }
        with self._lock:
            self._reuse_events.append(event)
        return event

    # ─── Panel Builders ────────────────────────────────────────────────────

    def get_activation_panel(self) -> Dict[str, Any]:
        """Returns the Activation Panel payload (shown on install)."""
        return {
            "type": "activation_panel",
            "status": "activated",
            "title": "✅ OpenMemo Activated",
            "subtitle": "Your agent now has memory.",
            "what_happens": [
                "Tasks will be remembered",
                "Workflows will be reused",
                "Performance improves over time",
            ],
            "actions": [
                {"label": "Run your first task", "action": "first_task"},
                {"label": "Customize memory", "action": "customize"},
            ],
            "installed_at": self._installed_at,
        }

    def get_status(self) -> Dict[str, Any]:
        """Returns current activation status for GET /activation/status."""
        with self._lock:
            return {
                "state": self._activation_state,
                "task_count": self._task_count,
                "total_stored": self._total_stored,
                "total_reused": self._total_reused,
                "total_steps_skipped": self._total_steps_skipped,
                "installed_at": self._installed_at,
                "latest_insight": self._insight_cards[-1] if self._insight_cards else None,
                "all_insights": list(self._insight_cards),
                "reuse_events": list(self._reuse_events),
            }

    def get_first_task(self) -> Dict[str, Any]:
        """Returns guided first task for GET /activation/first-task."""
        return {
            "type": "guided_first_task",
            "title": "Try your first task",
            "example": "Deploy a backend service",
            "hint": "Run it twice to see the difference.",
            "completed": self._task_count >= 1,
            "task_count": self._task_count,
        }

    # ─── Card Builders ─────────────────────────────────────────────────────

    def _card_memory_created(self, memories_stored: int, summary: str,
                             task_id: str) -> Dict[str, Any]:
        return {
            "type": "memory_created",
            "title": "🧠 Memory Created",
            "items": [
                f"Stored {memories_stored} workflow(s)" if memories_stored else "Stored task experience",
                "Stored task experience",
            ],
            "body": summary[:100] if summary else "",
            "task_id": task_id,
            "ts": int(time.time()),
        }

    def _card_optimization_detected(self, workflows_reused: int,
                                    steps_skipped: int, summary: str,
                                    task_id: str) -> Dict[str, Any]:
        items = []
        if workflows_reused:
            items.append(f"Reused {workflows_reused} workflow(s)")
        if steps_skipped:
            items.append(f"Skipped {steps_skipped} redundant step(s)")
        items.append("Faster execution")
        return {
            "type": "optimization_detected",
            "title": "⚡ Optimization Detected",
            "items": items,
            "body": summary[:100] if summary else "",
            "task_id": task_id,
            "ts": int(time.time()),
        }

    def _card_memory_updated(self, memories_stored: int, summary: str,
                             task_id: str) -> Dict[str, Any]:
        return {
            "type": "memory_updated",
            "title": "🧠 Memory Updated",
            "items": [
                f"Added {memories_stored} new memory(s)" if memories_stored else "Task experience stored",
                f"Total sessions: {self._task_count}",
            ],
            "body": summary[:100] if summary else "",
            "task_id": task_id,
            "ts": int(time.time()),
        }
