"""
Stats Tracker — records every kodara ask and calculates savings.

Storage: .kodara/stats.json (project-local, alongside the index)

Tracks:
  - Tokens actually sent (from ContextResult.token_estimate)
  - Tokens that WOULD have been sent (estimated full-project read)
  - Money saved at configurable price per 1M tokens

Default price: $15/1M tokens (GPT-4o / Claude Opus input pricing).
Override: KODARA_PRICE_PER_1M env var.
"""

from __future__ import annotations

import json
import os
import time
from dataclasses import dataclass, asdict
from datetime import datetime, date
from pathlib import Path
from typing import Optional


STATS_FILE = "stats.json"
DEFAULT_PRICE_PER_1M = 15.0   # USD, GPT-4o / Claude Opus input


@dataclass
class UsageEntry:
    ts: float              # Unix timestamp
    query: str             # truncated query
    tokens_used: int       # actual tokens sent to AI
    tokens_full: int       # estimated full-read tokens (without Kodara)
    tokens_saved: int      # tokens_full - tokens_used
    money_saved: float     # USD
    relevant_files: list   # which files were found (for query pattern analysis)


class StatsTracker:
    def __init__(self, kodara_dir: Path):
        self.path = kodara_dir / STATS_FILE
        self._price = float(os.getenv("KODARA_PRICE_PER_1M", DEFAULT_PRICE_PER_1M))

    def record(
        self,
        query: str,
        tokens_used: int,
        total_modules: int,
        modules_selected: int,
        index_total_files: int,
        relevant_files: list | None = None,
    ) -> UsageEntry:
        """
        Record one kodara ask call.

        tokens_full estimate: if AI had read all files proportionally.
        Average Python file ~200 lines ~800 tokens. We use that as baseline.
        """
        AVG_TOKENS_PER_FILE = 800
        tokens_full = index_total_files * AVG_TOKENS_PER_FILE
        tokens_saved = max(0, tokens_full - tokens_used)
        money_saved = (tokens_saved / 1_000_000) * self._price

        entry = UsageEntry(
            ts=time.time(),
            query=query[:80],
            tokens_used=tokens_used,
            tokens_full=tokens_full,
            tokens_saved=tokens_saved,
            money_saved=money_saved,
            relevant_files=relevant_files or [],
        )
        self._append(entry)
        return entry

    def summary(self) -> dict:
        entries = self._load()
        if not entries:
            return {"total_entries": 0}

        today_str = date.today().isoformat()
        month_str = date.today().strftime("%Y-%m")

        today = [e for e in entries if datetime.fromtimestamp(e["ts"]).date().isoformat() == today_str]
        month = [e for e in entries if datetime.fromtimestamp(e["ts"]).strftime("%Y-%m") == month_str]

        def agg(items: list[dict]) -> dict:
            if not items:
                return {"queries": 0, "tokens_saved": 0, "money_saved": 0.0}
            return {
                "queries": len(items),
                "tokens_used": sum(i["tokens_used"] for i in items),
                "tokens_saved": sum(i["tokens_saved"] for i in items),
                "money_saved": round(sum(i["money_saved"] for i in items), 4),
            }

        return {
            "total_entries": len(entries),
            "price_per_1m": self._price,
            "today": agg(today),
            "this_month": agg(month),
            "all_time": agg(entries),
        }

    def _append(self, entry: UsageEntry) -> None:
        entries = self._load()
        entries.append(asdict(entry))
        tmp = self.path.with_suffix(".tmp")
        tmp.write_text(json.dumps(entries, indent=2), encoding="utf-8")
        tmp.replace(self.path)

    def _load(self) -> list[dict]:
        if not self.path.exists():
            return []
        try:
            return json.loads(self.path.read_text(encoding="utf-8"))
        except Exception:
            return []
