"""ARIS Analytics — Track usage of skills, models, and tasks."""

import json
import os
import time
from pathlib import Path
from typing import Any, Optional


class AnalyticsStore:
    """Tracks ARIS usage metrics for ROI reporting."""

    def __init__(self, base_dir: Optional[str] = None) -> None:
        self._base = Path(base_dir or os.path.expanduser("~/.aris/analytics"))
        self._base.mkdir(parents=True, exist_ok=True)
        self._events_file = self._base / "events.json"
        self._events: list[dict[str, Any]] = self._load()

    def _load(self) -> list[dict[str, Any]]:
        if self._events_file.exists():
            try:
                return json.loads(self._events_file.read_text())
            except json.JSONDecodeError:
                pass
        return []

    def _save(self) -> None:
        self._events = self._events[-10000:]
        self._save_count = getattr(self, "_save_count", 0) + 1
        # Batch: write every 100 events
        if self._save_count < 100:
            return
        self.flush()

    def flush(self) -> None:
        """Force write to disk."""
        self._events = self._events[-10000:]
        self._events_file.write_text(json.dumps(self._events))
        self._save_count = 0

    def track(self, event_type: str, data: dict[str, Any]) -> None:
        self._events.append({"type": event_type, "data": data, "timestamp": time.time()})
        self._save()

    def track_skill_use(self, skill_name: str, tier: str) -> None:
        self.track("skill_used", {"skill": skill_name, "tier": tier})

    def track_route(self, task: str, models: list[str]) -> None:
        self.track("task_routed", {"task": task[:100], "models": models})

    def track_model_use(self, model: str, task_type: str) -> None:
        self.track("model_used", {"model": model, "task_type": task_type})

    def get_metrics(self, period: str = "7d") -> dict[str, Any]:
        cutoff = time.time() - self._period_seconds(period)
        recent = [e for e in self._events if e["timestamp"] > cutoff]

        skills_used: dict[str, int] = {}
        tasks_routed = 0
        models_used: dict[str, int] = {}

        for event in recent:
            if event["type"] == "skill_used":
                name = event["data"].get("skill", "unknown")
                skills_used[name] = skills_used.get(name, 0) + 1
            elif event["type"] == "task_routed":
                tasks_routed += 1
                for m in event["data"].get("models", []):
                    models_used[m] = models_used.get(m, 0) + 1
            elif event["type"] == "model_used":
                m = event["data"].get("model", "unknown")
                models_used[m] = models_used.get(m, 0) + 1

        time_saved_min = len(recent) * 3
        return {
            "period": period, "total_events": len(recent),
            "skills_used": sum(skills_used.values()),
            "skills_breakdown": dict(sorted(skills_used.items(), key=lambda x: -x[1])),
            "tasks_routed": tasks_routed,
            "models_used": dict(sorted(models_used.items(), key=lambda x: -x[1])),
            "estimated_time_saved": f"{round(time_saved_min / 60, 1)}h",
            "estimated_cost_saved": f"${round(tasks_routed * 0.02, 2)}",
        }

    def _period_seconds(self, period: str) -> float:
        multipliers = {"h": 3600, "d": 86400, "w": 604800}
        try:
            return int(period[:-1]) * multipliers.get(period[-1], 86400)
        except (ValueError, IndexError):
            return 604800
