#!/usr/bin/env python3
"""Antigravity PreInvocation hook: lightweight anti-silence nudge for long tool chains."""

from __future__ import annotations

from datetime import datetime
import json
import os
from pathlib import Path
import sys
from typing import Any

MARKER = "[进度轻推]"
NUDGE_TEXT = (
    "[进度轻推] 已连续多步静默调用工具，"
    "下一回合请先随工具调用输出 1 句中文进展，勿只回文字不调工具。"
)

DEFAULT_TURN_THRESHOLD = 5
DEFAULT_SECONDS_THRESHOLD = 60
DEFAULT_MAX_NUDGES = 1
TAIL_READ_BYTES = 262_144


def _env_int(name: str, default: int, minimum: int = 1) -> int:
    raw = os.environ.get(name)
    if raw is None or not raw.strip():
        return default
    try:
        return max(minimum, int(raw))
    except ValueError:
        return default


def parse_iso_epoch(ts_str: Any) -> float | None:
    if not isinstance(ts_str, str) or not ts_str:
        return None
    try:
        norm = ts_str[:-1] + "+00:00" if ts_str.endswith("Z") else ts_str
        return datetime.fromisoformat(norm).timestamp()
    except ValueError:
        return None


def resolve_transcript_path(payload: dict[str, Any]) -> Path | None:
    tp = payload.get("transcriptPath")
    if isinstance(tp, str) and tp:
        p = Path(tp)
        if p.is_file():
            return p
    cid = payload.get("conversationId")
    if isinstance(cid, str) and cid:
        p = (
            Path.home()
            / ".gemini"
            / "antigravity-cli"
            / "brain"
            / cid
            / ".system_generated"
            / "logs"
            / "transcript.jsonl"
        )
        if p.is_file():
            return p
    return None


def read_tail_lines(path: Path, max_bytes: int = TAIL_READ_BYTES) -> list[bytes]:
    size = path.stat().st_size
    if size <= 0:
        return []
    with open(path, "rb") as fb:
        seek_pos = max(0, size - max_bytes)
        fb.seek(seek_pos)
        chunk = fb.read()
    lines = chunk.splitlines()
    if seek_pos > 0 and lines:
        lines = lines[1:]
    return lines


def analyze_silence(
    lines: list[bytes],
    now_epoch: float,
    max_nudges: int = DEFAULT_MAX_NUDGES,
) -> tuple[int, float | None, int]:
    """Scan backward to the latest user turn, spoken planner reply, or checkpoint."""
    silent_turns = 0
    nudges_in_stretch = 0
    anchor_epoch: float | None = None
    oldest_epoch: float | None = None

    for raw in reversed(lines):
        if not raw.strip():
            continue
        try:
            obj = json.loads(raw.decode("utf-8", "replace"))
        except json.JSONDecodeError:
            continue

        ts = parse_iso_epoch(obj.get("created_at"))
        if ts is not None:
            oldest_epoch = ts

        stype = obj.get("type")
        if stype == "USER_INPUT":
            if anchor_epoch is None:
                anchor_epoch = ts
            break
        if stype == "CHECKPOINT":
            if anchor_epoch is None:
                anchor_epoch = ts
            break
        if stype == "SYSTEM_MESSAGE":
            if MARKER in str(obj.get("content") or ""):
                nudges_in_stretch += 1
                if anchor_epoch is None:
                    anchor_epoch = ts
                if nudges_in_stretch >= max_nudges:
                    break
            continue
        if stype == "PLANNER_RESPONSE":
            content = str(obj.get("content") or "").strip()
            if content:
                if anchor_epoch is None:
                    anchor_epoch = ts
                break
            if obj.get("tool_calls"):
                silent_turns += 1

    ref_epoch = anchor_epoch if anchor_epoch is not None else oldest_epoch
    silent_seconds = max(0.0, now_epoch - ref_epoch) if ref_epoch is not None else None
    return silent_turns, silent_seconds, nudges_in_stretch


def should_nudge(payload: dict[str, Any], now_epoch: float | None = None) -> bool:
    inv_num = payload.get("invocationNum")
    if isinstance(inv_num, int) and inv_num <= 1:
        return False

    tpath = resolve_transcript_path(payload)
    if tpath is None:
        return False

    turn_threshold = _env_int("AGY_SILENT_NUDGE_TURNS", DEFAULT_TURN_THRESHOLD)
    sec_threshold = _env_int("AGY_SILENT_NUDGE_SECONDS", DEFAULT_SECONDS_THRESHOLD)
    max_nudges = _env_int("AGY_SILENT_NUDGE_MAX", DEFAULT_MAX_NUDGES)

    lines = read_tail_lines(tpath)
    if not lines:
        return False

    now = datetime.now().timestamp() if now_epoch is None else now_epoch
    silent_turns, silent_seconds, nudges_in_stretch = analyze_silence(
        lines, now, max_nudges=max_nudges
    )
    if nudges_in_stretch >= max_nudges or silent_turns <= 0:
        return False
    if silent_turns >= turn_threshold:
        return True
    if silent_seconds is not None and silent_seconds >= sec_threshold:
        return True
    return False


def main() -> None:
    try:
        raw_in = sys.stdin.read()
        if not raw_in.strip():
            print("{}")
            return
        payload = json.loads(raw_in)
        if not isinstance(payload, dict) or not should_nudge(payload):
            print("{}")
            return
        print(
            json.dumps(
                {"injectSteps": [{"systemMessage": {"systemMessage": NUDGE_TEXT}}]},
                ensure_ascii=False,
            )
        )
    except Exception:
        print("{}")


if __name__ == "__main__":
    main()
