﻿"""Read-only collector for Antigravity transcript, DB, and quota metrics.

Reads:
  - ~/.gemini\\antigravity\\brain\\*\\.system_generated\\logs\\transcript.jsonl
  - ~/.gemini\\antigravity-cli\\brain\\*\\.system_generated\\logs\\transcript.jsonl
  - ~/.gemini\\antigravity-cli\\log\\cli-*.log (model backfill for CLI runs)
  - ~/.gemini\\antigravity\\conversation_summaries.db
  - ~/.gemini\\antigravity-cli\\quota_history.jsonl

Writes:
  - all_metrics.json in the same directory as this script.
"""

from __future__ import annotations

import argparse
import glob
import json
import math
import os
import re
import sqlite3
import statistics
import sys
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

AGY_TRANSCRIPT_GLOB = str(Path.home() / ".gemini" / "antigravity" / "brain" / "*" / ".system_generated" / "logs" / "transcript.jsonl")
CLI_TRANSCRIPT_GLOB = str(Path.home() / ".gemini" / "antigravity-cli" / "brain" / "*" / ".system_generated" / "logs" / "transcript.jsonl")
CLI_LOG_GLOB = str(Path.home() / ".gemini" / "antigravity-cli" / "log" / "cli-*.log")
SUMMARY_DB_PATH = str(Path.home() / ".gemini" / "antigravity" / "conversation_summaries.db")
QUOTA_HISTORY_PATH = str(Path.home() / ".gemini" / "antigravity-cli" / "quota_history.jsonl")

DEFAULT_OUTPUT_PATH = Path(__file__).resolve().parent / "all_metrics.json"
DEFAULT_ROLLOUT_CUTOFF = "2026-11-20T20:00:00Z"

# Synthetic cache-ladder probe sessions excluded from organic session telemetry.
SYNTHETIC_PROBE_CONVERSATIONS = frozenset({
    "4b023ea6-04f1-4756-968a-fc09659d2c62",
    "f5cbe013-1f8e-4d98-ad8a-a15adcc06f95",
    "c0d420f6-5f56-40fd-a358-257a9a18d5ff",
})

DECAY_BUCKETS = [
    ("0-15s", 0, 15, 7.5),
    ("15-30s", 15, 30, math.sqrt(15 * 30)),
    ("30-60s", 30, 60, math.sqrt(30 * 60)),
    ("1-2m", 60, 120, math.sqrt(60 * 120)),
    ("2-3m", 120, 180, math.sqrt(120 * 180)),
    ("3-5m", 180, 300, math.sqrt(180 * 300)),
    ("5-10m", 300, 600, math.sqrt(300 * 600)),
    ("10-15m", 600, 900, math.sqrt(600 * 900)),
    ("15-30m", 900, 1800, math.sqrt(900 * 1800)),
    ("30-60m", 1800, 3600, math.sqrt(1800 * 3600)),
    ("1-2h", 3600, 7200, math.sqrt(3600 * 7200)),
    ("2h+", 7200, float("inf"), 9600.0),
]

CACHE_RATE_BUCKETS = [
    ("0%", lambda r: r == 0.0),
    ("1-50%", lambda r: 0.0 < r < 0.50),
    ("50-75%", lambda r: 0.50 <= r < 0.75),
    ("75-90%", lambda r: 0.75 <= r < 0.90),
    ("90-95%", lambda r: 0.90 <= r < 0.95),
    ("95-99%", lambda r: 0.95 <= r < 0.99),
    ("99%+", lambda r: r >= 0.99),
]

CTX_BUCKETS = [
    ("<50k", 0, 50_000),
    ("50k-100k", 50_000, 100_000),
    ("100k-200k", 100_000, 200_000),
    ("200k-400k", 200_000, 400_000),
    ("400k-650k", 400_000, 650_000),
    ("650k+", 650_000, float("inf")),
]

LATENCY_CTX_BUCKETS = [
    ("<50k", 0, 50_000),
    ("50k-100k", 50_000, 100_000),
    ("100k-200k", 100_000, 200_000),
    ("200k-400k", 200_000, 400_000),
    ("400k+", 400_000, float("inf")),
]

IDLE_BUCKETS = [
    ("<1m", 0, 60),
    ("1-3m", 60, 180),
    ("3-5m", 180, 300),
    ("5-10m", 300, 600),
    ("10-30m", 600, 1800),
    ("30-60m", 1800, 3600),
    ("1h+", 3600, float("inf")),
]

QUOTA_KEYS = ["gemini-5h", "gemini-weekly", "3p-5h", "3p-weekly"]


def parse_ts(ts_str: str | None) -> float | None:
    if not ts_str:
        return None
    try:
        return datetime.fromisoformat(ts_str.replace("Z", "+00:00")).timestamp()
    except Exception:
        return None


def bucket_range(val: float, buckets: list[tuple[str, float, float]]) -> str:
    for name, lo, hi in buckets:
        if lo <= val < hi:
            return name
    return buckets[-1][0]


def decay_bucket(gap_sec: float) -> str:
    for name, lo, hi, _ in DECAY_BUCKETS:
        if lo <= gap_sec < hi:
            return name
    return "2h+"


def cache_rate_bucket(ratio: float) -> str:
    for name, pred in CACHE_RATE_BUCKETS:
        if pred(ratio):
            return name
    return "0%"


def percentile(sorted_vals: list[float], p: float) -> float | None:
    if not sorted_vals:
        return None
    n = len(sorted_vals)
    if n == 1:
        return float(sorted_vals[0])
    k = (n - 1) * (p / 100.0)
    f = math.floor(k)
    c = math.ceil(k)
    if f == c:
        return float(sorted_vals[int(k)])
    return sorted_vals[f] * (c - k) + sorted_vals[c] * (k - f)


def summarize_latency(vals: list[float]) -> dict[str, Any]:
    if not vals:
        return {"n": 0, "p50": None, "p90": None, "mean": None}
    s = sorted(vals)
    return {
        "n": len(s),
        "p50": round(percentile(s, 50), 2),
        "p90": round(percentile(s, 90), 2),
        "mean": round(sum(s) / len(s), 2),
    }


def load_conversation_metadata(db_path: str) -> dict[str, dict[str, str]]:
    """Load parent_conversation_id and title from conversation_summaries.db (read-only)."""
    meta: dict[str, dict[str, str]] = {}
    if not os.path.exists(db_path):
        return meta
    conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
    try:
        rows = conn.execute(
            "SELECT conversation_id, parent_conversation_id, title, preview FROM conversation_summaries"
        ).fetchall()
        for cid, parent_id, title, preview in rows:
            parent_id = parent_id or ""
            resolved_title = (title or "").strip() or (preview or "").strip()
            meta[cid] = {
                "role": "main" if parent_id == "" else "subagent",
                "parent_conversation_id": parent_id,
                "title": resolved_title,
            }
    finally:
        conn.close()
    return meta


def load_cli_model_map(log_glob: str) -> dict[str, str]:
    """Infer conversation_id -> model for CLI print-mode runs whose transcripts omit 'model'."""
    conv_models: dict[str, str] = {}
    start_re = re.compile(r'Print mode: starting \([^)]*model="([^"]*)"[^)]*conversationID="([^"]*)"')
    created_re = re.compile(r"Created conversation ([0-9a-f-]{36})")
    pm_conv_re = re.compile(r"Print mode: conversation=([0-9a-f-]{36})")

    for lp in sorted(glob.glob(log_glob)):
        try:
            txt = Path(lp).read_text(encoding="utf-8", errors="replace")
        except OSError:
            continue
        m = start_re.search(txt)
        if not m:
            continue
        model_id, cid = m.group(1).strip(), m.group(2).strip()
        if not model_id:
            continue
        if not cid:
            created = created_re.findall(txt) or pm_conv_re.findall(txt)
            if len(set(created)) == 1:
                cid = created[0]
        if cid:
            conv_models[cid] = model_id
    return conv_models


def discover_transcripts() -> tuple[list[dict[str, Any]], dict[str, int]]:
    """Discover and deduplicate transcripts across antigravity and antigravity-cli."""
    candidates: dict[str, list[dict[str, Any]]] = defaultdict(list)

    for source, pattern in [("antigravity", AGY_TRANSCRIPT_GLOB), ("antigravity-cli", CLI_TRANSCRIPT_GLOB)]:
        for p in sorted(glob.glob(pattern)):
            path = Path(p)
            cid = path.parts[-4]
            try:
                with open(path, "r", encoding="utf-8", errors="replace") as fh:
                    line_count = sum(1 for ln in fh if ln.strip())
            except OSError:
                continue
            candidates[cid].append({
                "conversation_id": cid,
                "source": source,
                "path": str(path),
                "line_count": line_count,
                "priority": 1 if source == "antigravity" else 0,
            })

    deduped = []
    dups = 0
    agy_kept = 0
    cli_kept = 0
    for cid in sorted(candidates):
        items = candidates[cid]
        if len(items) > 1:
            dups += len(items) - 1
        best = max(items, key=lambda x: (x["line_count"], x["priority"]))
        best["dups"] = max(0, len(items) - 1)
        deduped.append(best)
        if best["source"] == "antigravity":
            agy_kept += 1
        else:
            cli_kept += 1

    stats = {
        "transcripts_scanned": len(deduped),
        "antigravity_transcripts": agy_kept,
        "antigravity_cli_transcripts": cli_kept,
        "duplicates_deduped": dups,
    }
    return deduped, stats


def init_usage_agg() -> dict[str, Any]:
    return {
        "turns": 0,
        "total_ctx": 0,
        "input_tokens": 0,
        "cache_read_tokens": 0,
        "output_tokens": 0,
        "uncached_equiv": 0.0,
        "weighted_equiv": 0.0,
        "cold_lt50_turns": 0,
        "zero_cache_turns": 0,
        "sub90_turns": 0,
        "cache_ratio_sum": 0.0,
        "weighted_list": [],
    }


def add_usage_agg(agg: dict[str, Any], t: dict[str, Any]) -> None:
    agg["turns"] += 1
    agg["total_ctx"] += t["total_ctx"]
    agg["input_tokens"] += t["input_tokens"]
    agg["cache_read_tokens"] += t["cache_read_tokens"]
    agg["output_tokens"] += t["output_tokens"]
    agg["uncached_equiv"] += t["uncached_equiv"]
    agg["weighted_equiv"] += t["weighted_equiv"]
    if t["is_cold_lt50"]:
        agg["cold_lt50_turns"] += 1
    if t["is_zero_cache"]:
        agg["zero_cache_turns"] += 1
    if t["cache_ratio"] < 0.90:
        agg["sub90_turns"] += 1
    agg["cache_ratio_sum"] += t["cache_ratio"]
    agg["weighted_list"].append(t["weighted_equiv"])


def finalize_usage_agg(
    name: str,
    agg: dict[str, Any],
    total_turns: int,
    total_uncached: float,
    total_weighted: float,
) -> dict[str, Any]:
    n = agg["turns"]
    if n == 0:
        return {
            "name": name,
            "turns": 0,
            "turn_share_pct": 0.0,
            "cold_miss_lt50_count": 0,
            "zero_cache_count": 0,
            "sub90_count": 0,
            "sub90_pct": 0.0,
            "uncached_equiv_burn": 0,
            "uncached_share_pct": 0.0,
            "weighted_equiv_burn": 0,
            "weighted_share_pct": 0.0,
            "avg_uncached_burn": 0,
            "avg_weighted_burn": 0,
            "median_weighted_burn": 0,
            "avg_ctx": 0,
            "avg_cache_pct": 0.0,
            "eff_mult": 0.0,
            "eff_mult_weighted": 0.0,
        }
    eff_mult = (agg["uncached_equiv"] / (0.1 * agg["total_ctx"])) if agg["total_ctx"] > 0 else 10.0
    eff_mult_w = (agg["weighted_equiv"] / (0.1 * agg["total_ctx"])) if agg["total_ctx"] > 0 else 10.0
    return {
        "name": name,
        "turns": n,
        "turn_share_pct": round(n / total_turns * 100, 2) if total_turns else 0.0,
        "cold_miss_lt50_count": agg["cold_lt50_turns"],
        "zero_cache_count": agg["zero_cache_turns"],
        "sub90_count": agg["sub90_turns"],
        "sub90_pct": round(agg["sub90_turns"] / n * 100, 2),
        "uncached_equiv_burn": round(agg["uncached_equiv"]),
        "uncached_share_pct": round(agg["uncached_equiv"] / total_uncached * 100, 2) if total_uncached else 0.0,
        "weighted_equiv_burn": round(agg["weighted_equiv"]),
        "weighted_share_pct": round(agg["weighted_equiv"] / total_weighted * 100, 2) if total_weighted else 0.0,
        "avg_uncached_burn": round(agg["uncached_equiv"] / n),
        "avg_weighted_burn": round(agg["weighted_equiv"] / n),
        "median_weighted_burn": round(statistics.median(agg["weighted_list"])),
        "avg_ctx": round(agg["total_ctx"] / n),
        "avg_cache_pct": round((agg["cache_ratio_sum"] / n) * 100, 2),
        "eff_mult": round(eff_mult, 2),
        "eff_mult_weighted": round(eff_mult_w, 2),
    }


def build_latency_section(recs: list[dict[str, Any]]) -> dict[str, Any]:
    by_ctx = {}
    all_w, all_c = [], []
    for bname, _, _ in LATENCY_CTX_BUCKETS:
        sub = [r for r in recs if bucket_range(r["total_ctx"], LATENCY_CTX_BUCKETS) == bname]
        w = [r["latency_s"] for r in sub if r["cache_ratio"] >= 0.80]
        c = [r["latency_s"] for r in sub if r["cache_read_tokens"] == 0]
        all_w.extend(w)
        all_c.extend(c)
        ws, cs = summarize_latency(w), summarize_latency(c)
        delta = round(cs["p50"] - ws["p50"], 2) if (cs["p50"] is not None and ws["p50"] is not None) else None
        by_ctx[bname] = {"warm": ws, "cold": cs, "delta_p50": delta}

    ws_all, cs_all = summarize_latency(all_w), summarize_latency(all_c)
    by_ctx["ALL"] = {
        "warm": ws_all,
        "cold": cs_all,
        "delta_p50": round(cs_all["p50"] - ws_all["p50"], 2)
        if (cs_all["p50"] is not None and ws_all["p50"] is not None)
        else None,
    }

    by_model = {}
    for m in sorted({r["model"] for r in recs}):
        sub = [r for r in recs if r["model"] == m]
        w = [r["latency_s"] for r in sub if r["cache_ratio"] >= 0.80]
        c = [r["latency_s"] for r in sub if r["cache_read_tokens"] == 0]
        if not w and not c:
            continue
        ws, cs = summarize_latency(w), summarize_latency(c)
        delta = round(cs["p50"] - ws["p50"], 2) if (cs["p50"] is not None and ws["p50"] is not None) else None
        by_model[m] = {"warm": ws, "cold": cs, "delta_p50": delta}

    return {"by_context_bucket": by_ctx, "by_model": by_model}


def compute_quota_deltas(
    quota_path: str,
    turns_timeline: list[dict[str, Any]],
) -> dict[str, Any]:
    if not os.path.exists(quota_path):
        return {"present": False, "entries": 0, "intervals": []}

    entries = []
    with open(quota_path, "r", encoding="utf-8", errors="replace") as fh:
        for line in fh:
            line = line.strip()
            if not line:
                continue
            try:
                obj = json.loads(line)
            except json.JSONDecodeError:
                continue
            ts = parse_ts(obj.get("ts"))
            if ts is not None:
                obj["_ts_epoch"] = ts
                entries.append(obj)

    entries.sort(key=lambda x: x["_ts_epoch"])
    intervals = []
    for i in range(1, len(entries)):
        prev = entries[i - 1]
        curr = entries[i]
        t0, t1 = prev["_ts_epoch"], curr["_ts_epoch"]
        q0 = prev.get("quota") or {}
        q1 = curr.get("quota") or {}

        matched_turns = [
            t for t in turns_timeline
            if t["ts_epoch"] is not None and t0 < t["ts_epoch"] <= t1
        ]

        tr_in = sum(t["input_tokens"] for t in matched_turns)
        tr_cr = sum(t["cache_read_tokens"] for t in matched_turns)
        tr_out = sum(t["output_tokens"] for t in matched_turns)
        tr_tot_in = tr_in + tr_cr
        tr_tot_all = tr_tot_in + tr_out
        tr_unc_eq = sum(t["uncached_equiv"] for t in matched_turns)
        tr_w_eq = sum(t["weighted_equiv"] for t in matched_turns)

        cw = curr.get("context_window") or {}
        cu = cw.get("current_usage") or {}
        cu_in = int(cu.get("input_tokens") or 0)
        cu_cr = int(cu.get("cache_read_input_tokens") or 0)
        cu_cc = int(cu.get("cache_creation_input_tokens") or 0)
        cu_out = int(cu.get("output_tokens") or 0)
        cu_tot_in = cu_in + cu_cr + cu_cc
        cu_tot_all = cu_tot_in + cu_out

        # Use transcript sum when available, falling back to current_usage if needed
        eff_in = tr_in if matched_turns else cu_in
        eff_tot_in = tr_tot_in if matched_turns else cu_tot_in
        eff_tot_all = tr_tot_all if matched_turns else cu_tot_all
        eff_unc_eq = tr_unc_eq if matched_turns else (cu_in + cu_cc + 0.1 * cu_cr)

        deltas = {}
        drop_per_1m = {}
        for k in QUOTA_KEYS:
            v0 = q0.get(k)
            v1 = q1.get(k)
            if v0 is None or v1 is None:
                deltas[k] = None
                drop_per_1m[k] = None
                continue
            delta = round(v1 - v0, 10)
            drop = round(v0 - v1, 10)
            deltas[k] = {
                "prev": v0,
                "curr": v1,
                "delta": delta,
                "drop": drop,
                "drop_pct_pts": round(drop * 100, 6),
            }
            drop_per_1m[k] = {
                "per_1m_uncached_input": round(drop / (eff_in / 1e6), 6) if eff_in > 0 else None,
                "per_1m_uncached_input_pct_pts": round((drop / (eff_in / 1e6)) * 100, 4) if eff_in > 0 else None,
                "per_1m_total_input": round(drop / (eff_tot_in / 1e6), 6) if eff_tot_in > 0 else None,
                "per_1m_total_tokens": round(drop / (eff_tot_all / 1e6), 6) if eff_tot_all > 0 else None,
                "per_1m_total_tokens_pct_pts": round((drop / (eff_tot_all / 1e6)) * 100, 4) if eff_tot_all > 0 else None,
                "per_1m_uncached_equiv": round(drop / (eff_unc_eq / 1e6), 6) if eff_unc_eq > 0 else None,
            }

        intervals.append({
            "interval_index": i - 1,
            "start_ts": prev.get("ts"),
            "end_ts": curr.get("ts"),
            "duration_sec": round(t1 - t0, 3),
            "statusline_conversation_id": curr.get("conversation_id"),
            "statusline_model": curr.get("model"),
            "statusline_current_usage": cu if cu else None,
            "transcript_turns_in_window": [
                {
                    "conversation_id": t["conversation_id"],
                    "title": t["title"],
                    "role": t["role"],
                    "step_index": t["step_index"],
                    "created_at": t["created_at"],
                    "model": t["model"],
                    "input_tokens": t["input_tokens"],
                    "cache_read_tokens": t["cache_read_tokens"],
                    "output_tokens": t["output_tokens"],
                }
                for t in matched_turns
            ],
            "window_tokens": {
                "transcript_turn_count": len(matched_turns),
                "transcript_input_tokens": tr_in,
                "transcript_cache_read_tokens": tr_cr,
                "transcript_output_tokens": tr_out,
                "transcript_total_input_tokens": tr_tot_in,
                "transcript_total_tokens": tr_tot_all,
                "transcript_uncached_equiv": round(tr_unc_eq, 2),
                "transcript_weighted_equiv": round(tr_w_eq, 2),
                "statusline_input_tokens": cu_in,
                "statusline_cache_read_tokens": cu_cr,
                "statusline_output_tokens": cu_out,
                "statusline_total_tokens": cu_tot_all,
            },
            "quota_deltas": deltas,
            "quota_drop_per_1m_tokens": drop_per_1m,
        })

    return {
        "present": True,
        "entries": len(entries),
        "intervals": intervals,
    }


class PeriodAccumulator:
    """Accumulates transcript, decay, usage, and latency metrics for one time window."""

    def __init__(self, excluded_probes: int = 0) -> None:
        self.excluded_probes = excluded_probes
        self.seen_transcripts: dict[str, dict[str, Any]] = {}
        self.role_convs: dict[str, set[str]] = {r: set() for r in ("main", "subagent", "unknown")}

        self.total_planner_responses = 0
        self.total_turns_with_tokens = 0
        self.total_cached_tokens = 0
        self.total_uncached_input_tokens = 0
        self.total_output_tokens = 0
        self.total_uncached_equiv = 0.0
        self.total_weighted_equiv = 0.0

        self.role_split: dict[str, dict[str, Any]] = {
            r: {
                "conversations": 0,
                "turns": 0,
                "cached_tokens": 0,
                "uncached_input_tokens": 0,
                "output_tokens": 0,
                "total_context_tokens": 0,
                "uncached_equiv_burn": 0.0,
                "weighted_equiv_burn": 0.0,
            }
            for r in ("main", "subagent", "unknown")
        }

        # Decay accumulators: [total, hits, sum_ratio, sum_cached_tok, sum_uncached_tok]
        self.decay_all = defaultdict(lambda: defaultdict(lambda: [0, 0, 0.0, 0, 0]))
        self.decay_nonshrink = defaultdict(lambda: defaultdict(lambda: [0, 0, 0.0, 0, 0]))
        self.decay_model_overall = defaultdict(lambda: {
            "steps": 0, "hits": 0, "cached_tokens": 0, "uncached_tokens": 0,
            "output_tokens": 0, "contexts": [], "min_ts": "9999", "max_ts": "0000",
        })
        self.decay_longest_hits: dict[str, dict[str, Any]] = {}

        self.cache_aggs = {name: init_usage_agg() for name, _ in CACHE_RATE_BUCKETS}
        self.split_90 = {"ge90": init_usage_agg(), "lt90": init_usage_agg()}
        self.ctx_aggs = {name: init_usage_agg() for name, _, _ in CTX_BUCKETS}
        self.idle_aggs = {name: init_usage_agg() for name, _, _ in IDLE_BUCKETS}

        self.cold_misses_all: list[dict[str, Any]] = []
        self.latency_all_pr: list[dict[str, Any]] = []
        self.latency_post_user: list[dict[str, Any]] = []
        self.turns_timeline: list[dict[str, Any]] = []

    def mark_transcript(self, item: dict[str, Any], role: str) -> None:
        cid = item["conversation_id"]
        if cid not in self.seen_transcripts:
            self.seen_transcripts[cid] = item
        self.role_convs[role].add(cid)

    def add_planner_response(self, item: dict[str, Any], role: str) -> None:
        self.mark_transcript(item, role)
        self.total_planner_responses += 1

    def add_turn(
        self,
        rec: dict[str, Any],
        resolved_model: str,
        lat_rec: dict[str, Any] | None,
        is_post_user: bool,
    ) -> None:
        self.total_turns_with_tokens += 1
        inp = rec["input_tokens"]
        cr = rec["cache_read_tokens"]
        out = rec["output_tokens"]
        total_ctx = rec["total_ctx"]
        ts_str = rec["created_at"]
        role = rec["role"]

        self.total_cached_tokens += cr
        self.total_uncached_input_tokens += inp
        self.total_output_tokens += out
        self.total_uncached_equiv += rec["uncached_equiv"]
        self.total_weighted_equiv += rec["weighted_equiv"]

        rs = self.role_split[role]
        rs["turns"] += 1
        rs["cached_tokens"] += cr
        rs["uncached_input_tokens"] += inp
        rs["output_tokens"] += out
        rs["total_context_tokens"] += total_ctx
        rs["uncached_equiv_burn"] += rec["uncached_equiv"]
        rs["weighted_equiv_burn"] += rec["weighted_equiv"]

        ov = self.decay_model_overall[resolved_model]
        ov["steps"] += 1
        if cr > 0:
            ov["hits"] += 1
        ov["cached_tokens"] += cr
        ov["uncached_tokens"] += inp
        ov["output_tokens"] += out
        ov["contexts"].append(total_ctx)
        if ts_str:
            if ts_str < ov["min_ts"]:
                ov["min_ts"] = ts_str
            if ts_str > ov["max_ts"]:
                ov["max_ts"] = ts_str

        self.turns_timeline.append(rec)

        cache_ratio = rec["cache_ratio"]
        add_usage_agg(self.cache_aggs[cache_rate_bucket(cache_ratio)], rec)
        add_usage_agg(self.split_90["ge90" if cache_ratio >= 0.90 else "lt90"], rec)
        add_usage_agg(self.ctx_aggs[bucket_range(total_ctx, CTX_BUCKETS)], rec)
        if rec["gap_sec"] is not None:
            add_usage_agg(self.idle_aggs[bucket_range(rec["gap_sec"], IDLE_BUCKETS)], rec)

        if rec["is_cold_lt50"]:
            self.cold_misses_all.append(rec)

        if lat_rec is not None:
            self.latency_all_pr.append(lat_rec)
            if is_post_user:
                self.latency_post_user.append(lat_rec)

    def add_decay_pair(self, cid: str, prev: dict[str, Any], curr: dict[str, Any]) -> None:
        gap = curr["ts"] - prev["ts"]
        if gap < 0:
            return
        m = curr["model"]
        b = decay_bucket(gap)
        hit = 1 if curr["cache_tok"] > 0 else 0
        ratio = curr["cache_tok"] / curr["total_in"]
        shrunk = curr["total_in"] < prev["total_in"]

        ba = self.decay_all[m][b]
        ba[0] += 1
        ba[1] += hit
        ba[2] += ratio
        ba[3] += curr["cache_tok"]
        ba[4] += curr["in_tok"]

        if not shrunk:
            bn = self.decay_nonshrink[m][b]
            bn[0] += 1
            bn[1] += hit
            bn[2] += ratio
            bn[3] += curr["cache_tok"]
            bn[4] += curr["in_tok"]

        if hit and (m not in self.decay_longest_hits or gap > self.decay_longest_hits[m]["gap_sec"]):
            self.decay_longest_hits[m] = {
                "gap_sec": round(gap, 1),
                "conversation_id": cid,
                "prev_step": prev["step_index"],
                "curr_step": curr["step_index"],
                "prev_total_in": prev["total_in"],
                "curr_total_in": curr["total_in"],
                "cache_tok": curr["cache_tok"],
                "in_tok": curr["in_tok"],
                "ts": curr["ts_str"],
            }

    def finalize(self, quota_deltas: dict[str, Any]) -> dict[str, Any]:
        agy_count = sum(1 for it in self.seen_transcripts.values() if it["source"] == "antigravity")
        cli_count = sum(1 for it in self.seen_transcripts.values() if it["source"] == "antigravity-cli")
        dups_count = sum(it.get("dups", 0) for it in self.seen_transcripts.values())
        scan_stats = {
            "transcripts_scanned": len(self.seen_transcripts),
            "antigravity_transcripts": agy_count,
            "antigravity_cli_transcripts": cli_count,
            "duplicates_deduped": dups_count,
            "excluded_probe_transcripts": self.excluded_probes,
        }

        total_ctx_all = self.total_cached_tokens + self.total_uncached_input_tokens
        main_vs_subagent_out = {}
        for r, rs in self.role_split.items():
            tot_r = rs["total_context_tokens"]
            main_vs_subagent_out[r] = {
                "conversations": len(self.role_convs[r]),
                "turns": rs["turns"],
                "cached_tokens": rs["cached_tokens"],
                "uncached_input_tokens": rs["uncached_input_tokens"],
                "output_tokens": rs["output_tokens"],
                "total_context_tokens": tot_r,
                "cache_pct": round(rs["cached_tokens"] / tot_r * 100, 2) if tot_r else 0.0,
                "uncached_equiv_burn": round(rs["uncached_equiv_burn"]),
                "weighted_equiv_burn": round(rs["weighted_equiv_burn"]),
                "share_of_turns_pct": round(rs["turns"] / self.total_turns_with_tokens * 100, 2) if self.total_turns_with_tokens else 0.0,
                "share_of_context_pct": round(tot_r / total_ctx_all * 100, 2) if total_ctx_all else 0.0,
                "share_of_uncached_equiv_pct": round(rs["uncached_equiv_burn"] / self.total_uncached_equiv * 100, 2) if self.total_uncached_equiv else 0.0,
                "share_of_weighted_equiv_pct": round(rs["weighted_equiv_burn"] / self.total_weighted_equiv * 100, 2) if self.total_weighted_equiv else 0.0,
            }

        overview = {
            **scan_stats,
            "planner_response_turns": self.total_planner_responses,
            "turns_with_tokens": self.total_turns_with_tokens,
            "total_cached_tokens": self.total_cached_tokens,
            "total_uncached_input_tokens": self.total_uncached_input_tokens,
            "total_output_tokens": self.total_output_tokens,
            "total_context_tokens": total_ctx_all,
            "overall_token_cache_pct": round(self.total_cached_tokens / total_ctx_all * 100, 2) if total_ctx_all else 0.0,
            "total_uncached_equiv_burn": round(self.total_uncached_equiv),
            "total_weighted_equiv_burn": round(self.total_weighted_equiv),
            "main_vs_subagent": main_vs_subagent_out,
        }

        models_out = {}
        for m, ov in sorted(self.decay_model_overall.items(), key=lambda x: -x[1]["steps"]):
            ctxs = sorted(ov["contexts"])
            tot_tok = ov["cached_tokens"] + ov["uncached_tokens"]
            all_pts = []
            nonshrink_pts = []
            for bname, _, _, mid in DECAY_BUCKETS:
                cnt, hits, sratio, ctok, itok = self.decay_all[m][bname]
                if cnt > 0:
                    all_pts.append({
                        "bucket": bname,
                        "mid_s": round(mid, 2),
                        "total": cnt,
                        "hits": hits,
                        "hit_rate": round(hits / cnt * 100, 2),
                        "avg_cache_ratio": round(sratio / cnt * 100, 2),
                        "tok_cache_pct": round(ctok / (ctok + itok) * 100, 2) if (ctok + itok) else 0.0,
                    })
                cnt_n, hits_n, sratio_n, ctok_n, itok_n = self.decay_nonshrink[m][bname]
                if cnt_n > 0:
                    nonshrink_pts.append({
                        "bucket": bname,
                        "mid_s": round(mid, 2),
                        "total": cnt_n,
                        "hits": hits_n,
                        "hit_rate": round(hits_n / cnt_n * 100, 2),
                        "avg_cache_ratio": round(sratio_n / cnt_n * 100, 2),
                        "tok_cache_pct": round(ctok_n / (ctok_n + itok_n) * 100, 2) if (ctok_n + itok_n) else 0.0,
                    })

            models_out[m] = {
                "overall": {
                    "steps": ov["steps"],
                    "hits": ov["hits"],
                    "step_hit_rate": round(ov["hits"] / ov["steps"] * 100, 2) if ov["steps"] else 0.0,
                    "cached_tokens": ov["cached_tokens"],
                    "uncached_tokens": ov["uncached_tokens"],
                    "overall_cache_pct": round(ov["cached_tokens"] / tot_tok * 100, 2) if tot_tok else 0.0,
                    "median_context": int(statistics.median(ctxs)) if ctxs else 0,
                    "p90_context": int(ctxs[int(0.9 * (len(ctxs) - 1))]) if ctxs else 0,
                    "max_context": max(ctxs) if ctxs else 0,
                    "min_ts": ov["min_ts"],
                    "max_ts": ov["max_ts"],
                },
                "longest_hit": self.decay_longest_hits.get(m),
                "all_turns": all_pts,
                "no_context_shrink": nonshrink_pts,
            }

        cache_decay_by_model = {
            "buckets_meta": [
                {"id": bname, "lo": lo, "hi": None if hi == float("inf") else hi, "mid_s": round(mid, 2)}
                for bname, lo, hi, mid in DECAY_BUCKETS
            ],
            "models": models_out,
        }

        cache_rate_vs_usage = {
            "buckets": [
                finalize_usage_agg(name, self.cache_aggs[name], self.total_turns_with_tokens, self.total_uncached_equiv, self.total_weighted_equiv)
                for name, _ in CACHE_RATE_BUCKETS
            ],
            "summary_90pct": {
                "ge90": finalize_usage_agg("ge90", self.split_90["ge90"], self.total_turns_with_tokens, self.total_uncached_equiv, self.total_weighted_equiv),
                "lt90": finalize_usage_agg("lt90", self.split_90["lt90"], self.total_turns_with_tokens, self.total_uncached_equiv, self.total_weighted_equiv),
            },
        }

        top5_cold = sorted(self.cold_misses_all, key=lambda x: -x["weighted_equiv"])[:5]
        context_size_vs_usage = {
            "buckets": [
                finalize_usage_agg(name, self.ctx_aggs[name], self.total_turns_with_tokens, self.total_uncached_equiv, self.total_weighted_equiv)
                for name, _, _ in CTX_BUCKETS
            ],
            "top_5_costliest_cold_misses": [
                {
                    "conversation_id": r["conversation_id"],
                    "title": r["title"],
                    "role": r["role"],
                    "step_index": r["step_index"],
                    "created_at": r["created_at"],
                    "model": r["model"],
                    "gap_sec": round(r["gap_sec"], 1) if r["gap_sec"] is not None else None,
                    "input_tokens": r["input_tokens"],
                    "cache_read_tokens": r["cache_read_tokens"],
                    "total_ctx": r["total_ctx"],
                    "cache_pct": round(r["cache_ratio"] * 100, 2),
                    "uncached_equiv_burn": round(r["uncached_equiv"]),
                    "weighted_equiv_burn": round(r["weighted_equiv"]),
                }
                for r in top5_cold
            ],
        }

        idle_measured_turns = sum(self.idle_aggs[name]["turns"] for name, _, _ in IDLE_BUCKETS)
        idle_unc_total = sum(self.idle_aggs[name]["uncached_equiv"] for name, _, _ in IDLE_BUCKETS)
        idle_w_total = sum(self.idle_aggs[name]["weighted_equiv"] for name, _, _ in IDLE_BUCKETS)
        idle_time_vs_usage = {
            "idle_measured_turns": idle_measured_turns,
            "buckets": [
                finalize_usage_agg(name, self.idle_aggs[name], idle_measured_turns, idle_unc_total, idle_w_total)
                for name, _, _ in IDLE_BUCKETS
            ],
        }

        cold_miss_latency = {
            "definition": "next_non_user_step.created_at - PLANNER_RESPONSE.created_at (excluding Step 1, filtered 0 <= lat <= 600s; warm >= 80% cache, cold == 0% cache)",
            "all_planner_turns": build_latency_section(self.latency_all_pr),
            "post_user_input_turns": build_latency_section(self.latency_post_user),
        }

        return {
            "overview": overview,
            "cache_decay_by_model": cache_decay_by_model,
            "cache_rate_vs_usage": cache_rate_vs_usage,
            "context_size_vs_usage": context_size_vs_usage,
            "idle_time_vs_usage": idle_time_vs_usage,
            "cold_miss_latency": cold_miss_latency,
            "quota_deltas": quota_deltas,
        }


def filter_quota_deltas(quota_deltas: dict[str, Any], cutoff_epoch: float, keep_after: bool) -> dict[str, Any]:
    if not quota_deltas.get("present"):
        return quota_deltas
    filtered = []
    for iv in quota_deltas.get("intervals", []):
        end_ts = parse_ts(iv.get("end_ts"))
        if end_ts is None:
            continue
        is_after = end_ts >= cutoff_epoch
        if is_after == keep_after:
            filtered.append(iv)
    return {
        "present": True,
        "entries": quota_deltas.get("entries", 0),
        "intervals": filtered,
    }


def collect_all_metrics(
    output_path: Path = DEFAULT_OUTPUT_PATH,
    cutoff_str: str = DEFAULT_ROLLOUT_CUTOFF,
    include_probes: bool = False,
) -> dict[str, Any]:
    cutoff_epoch = parse_ts(cutoff_str)
    if cutoff_epoch is None:
        raise ValueError(f"Invalid ISO-8601 cutoff timestamp: {cutoff_str!r}")

    conv_meta = load_conversation_metadata(SUMMARY_DB_PATH)
    cli_models = load_cli_model_map(CLI_LOG_GLOB)
    all_transcripts, _ = discover_transcripts()

    if include_probes:
        transcripts = all_transcripts
        excluded_probe_ids: list[str] = []
    else:
        transcripts = [t for t in all_transcripts if t["conversation_id"] not in SYNTHETIC_PROBE_CONVERSATIONS]
        excluded_probe_ids = sorted(
            t["conversation_id"] for t in all_transcripts if t["conversation_id"] in SYNTHETIC_PROBE_CONVERSATIONS
        )

    all_acc = PeriodAccumulator(excluded_probes=len(excluded_probe_ids))
    before_acc = PeriodAccumulator(excluded_probes=len(excluded_probe_ids))
    after_acc = PeriodAccumulator(excluded_probes=len(excluded_probe_ids))

    for item in transcripts:
        cid = item["conversation_id"]
        meta = conv_meta.get(cid)
        role = meta["role"] if meta else "unknown"
        title = meta["title"] if meta else ""
        all_acc.mark_transcript(item, role)

        steps: list[dict[str, Any]] = []
        with open(item["path"], "r", encoding="utf-8", errors="replace") as fh:
            for line in fh:
                line = line.strip()
                if not line:
                    continue
                try:
                    steps.append(json.loads(line))
                except json.JSONDecodeError:
                    continue

        pr_steps_for_decay: list[dict[str, Any]] = []
        prev_pr_ts: float | None = None
        last_known_model: str | None = cli_models.get(cid)

        for idx, obj in enumerate(steps):
            if obj.get("type") != "PLANNER_RESPONSE":
                continue

            ts_str = obj.get("created_at")
            ts_epoch = parse_ts(ts_str)
            is_after = ts_epoch is not None and ts_epoch >= cutoff_epoch
            period_acc = after_acc if is_after else before_acc

            all_acc.add_planner_response(item, role)
            period_acc.add_planner_response(item, role)

            raw_model = obj.get("model")
            if raw_model:
                last_known_model = raw_model
            resolved_model = raw_model or cli_models.get(cid) or "<missing>"
            resolved_model_carry = raw_model or last_known_model or "<missing>"

            inp_raw = obj.get("input_tokens")
            cr_raw = obj.get("cache_read_tokens")
            out_raw = obj.get("output_tokens")

            if inp_raw is None and cr_raw is None:
                continue

            inp = int(inp_raw or 0)
            cr = int(cr_raw or 0)
            out = int(out_raw or 0)
            total_ctx = inp + cr

            if ts_epoch is not None:
                pr_steps_for_decay.append({
                    "step_index": obj.get("step_index"),
                    "model": resolved_model,
                    "in_tok": inp,
                    "cache_tok": cr,
                    "out_tok": out,
                    "total_in": total_ctx,
                    "ts": ts_epoch,
                    "ts_str": ts_str,
                })

            if total_ctx <= 0:
                continue

            cache_ratio = cr / total_ctx
            uncached_equiv = inp + 0.1 * cr
            tier_mult = 2.0 if total_ctx > 200_000 else 1.0
            weighted_equiv = uncached_equiv * tier_mult

            gap_sec = (ts_epoch - prev_pr_ts) if (ts_epoch is not None and prev_pr_ts is not None) else None
            if gap_sec is not None and gap_sec < 0:
                gap_sec = 0.0

            rec = {
                "conversation_id": cid,
                "title": title,
                "role": role,
                "step_index": obj.get("step_index"),
                "created_at": ts_str,
                "ts_epoch": ts_epoch,
                "model": resolved_model_carry,
                "input_tokens": inp,
                "cache_read_tokens": cr,
                "output_tokens": out,
                "total_ctx": total_ctx,
                "cache_ratio": cache_ratio,
                "uncached_equiv": uncached_equiv,
                "weighted_equiv": weighted_equiv,
                "is_cold_lt50": cache_ratio < 0.50,
                "is_zero_cache": cr == 0,
                "gap_sec": gap_sec,
            }

            if ts_epoch is not None:
                prev_pr_ts = ts_epoch

            lat_rec: dict[str, Any] | None = None
            is_post_user = False
            is_step1 = (obj.get("step_index") == 1) or (
                idx == 1 and steps[0].get("type") == "USER_INPUT" and steps[0].get("step_index") == 0
            )
            if not is_step1 and ts_epoch is not None and idx + 1 < len(steps):
                nxt = steps[idx + 1]
                if nxt.get("type") != "USER_INPUT":
                    t_nxt = parse_ts(nxt.get("created_at"))
                    if t_nxt is not None:
                        lat = t_nxt - ts_epoch
                        if 0 <= lat <= 600:
                            lat_rec = {
                                "latency_s": lat,
                                "total_ctx": total_ctx,
                                "cache_ratio": cache_ratio,
                                "cache_read_tokens": cr,
                                "model": resolved_model,
                            }
                            is_post_user = idx > 0 and steps[idx - 1].get("type") == "USER_INPUT"

            all_acc.add_turn(rec, resolved_model, lat_rec, is_post_user)
            period_acc.add_turn(rec, resolved_model, lat_rec, is_post_user)

        for i in range(1, len(pr_steps_for_decay)):
            prev = pr_steps_for_decay[i - 1]
            curr = pr_steps_for_decay[i]
            if prev["model"] != curr["model"]:
                continue
            if prev["total_in"] + prev["out_tok"] <= 0 or curr["total_in"] <= 0:
                continue
            if curr["ts"] < prev["ts"]:
                continue

            all_acc.add_decay_pair(cid, prev, curr)
            if curr["ts"] < cutoff_epoch:
                before_acc.add_decay_pair(cid, prev, curr)
            elif prev["ts"] >= cutoff_epoch:
                after_acc.add_decay_pair(cid, prev, curr)

    quota_all = compute_quota_deltas(QUOTA_HISTORY_PATH, all_acc.turns_timeline)
    quota_before = filter_quota_deltas(quota_all, cutoff_epoch, keep_after=False)
    quota_after = filter_quota_deltas(quota_all, cutoff_epoch, keep_after=True)

    all_section = all_acc.finalize(quota_all)
    before_section = before_acc.finalize(quota_before)
    after_section = after_acc.finalize(quota_after)

    payload = {
        "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
        "cutoff": cutoff_str,
        "excluded_probe_conversations": excluded_probe_ids,
        **all_section,
        "periods": {
            "cutoff": cutoff_str,
            "before": before_section,
            "after": after_section,
        },
    }

    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
    return payload


def _print_period_summary(label: str, section: dict[str, Any]) -> None:
    ov = section["overview"]
    print(
        f"[{label}] Transcripts: {ov['transcripts_scanned']} "
        f"(agy={ov['antigravity_transcripts']}, cli={ov['antigravity_cli_transcripts']}, "
        f"deduped={ov['duplicates_deduped']}) | "
        f"Turns: {ov['planner_response_turns']} ({ov['turns_with_tokens']} w/ tokens) | "
        f"Cache: {ov['overall_token_cache_pct']}%"
    )


def main() -> None:
    parser = argparse.ArgumentParser(description="Collect Antigravity cache, burn, latency, and quota metrics.")
    parser.add_argument(
        "--cutoff",
        default=DEFAULT_ROLLOUT_CUTOFF,
        help=f"ISO-8601 UTC rollout cutoff timestamp (default: {DEFAULT_ROLLOUT_CUTOFF})",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=DEFAULT_OUTPUT_PATH,
        help=f"Output JSON path (default: {DEFAULT_OUTPUT_PATH})",
    )
    parser.add_argument(
        "--include-probes",
        action="store_true",
        help="Include synthetic probe conversations in organic stats",
    )
    args = parser.parse_args()

    try:
        payload = collect_all_metrics(
            output_path=args.output,
            cutoff_str=args.cutoff,
            include_probes=args.include_probes,
        )
    except ValueError as exc:
        print(f"Error: {exc}", file=sys.stderr)
        sys.exit(2)

    print(f"Wrote {args.output} (cutoff={payload['cutoff']}, excluded_probes={len(payload['excluded_probe_conversations'])})")
    _print_period_summary("all", payload)
    _print_period_summary("before", payload["periods"]["before"])
    _print_period_summary("after", payload["periods"]["after"])

    ov = payload["overview"]
    for role, rs in ov["main_vs_subagent"].items():
        print(
            f"  [{role}] convs={rs['conversations']} turns={rs['turns']} "
            f"cached={rs['cached_tokens']:,} uncached={rs['uncached_input_tokens']:,} "
            f"cache%={rs['cache_pct']}% unc_eq_share={rs['share_of_uncached_equiv_pct']}%"
        )
    qd = payload["quota_deltas"]
    print(f"Quota intervals: {len(qd.get('intervals', []))}")
    for iv in qd.get("intervals", []):
        print(f"  Interval {iv['interval_index']} ({iv['start_ts']} -> {iv['end_ts']}):")
        for k, d in iv["quota_deltas"].items():
            if d and d["drop"] != 0:
                p1m = iv["quota_drop_per_1m_tokens"][k]
                print(f"    {k}: delta={d['delta']} (drop={d['drop']}), per_1m_in={p1m['per_1m_uncached_input']}, per_1m_tot={p1m['per_1m_total_tokens']}")


if __name__ == "__main__":
    main()

