#!/usr/bin/env python3

import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from droid_transcript import find_last_assistant_text


def log_dir() -> Path:
    override = os.environ.get("KG_DROID_HOOK_LOG_DIR")
    if override:
        return Path(override).expanduser()
    return Path.home() / ".factory" / "kg-droid-hook"


def main() -> int:
    try:
        payload = json.load(sys.stdin)
    except json.JSONDecodeError as exc:
        print(f"invalid hook input: {exc}", file=sys.stderr)
        return 1

    out_dir = log_dir()
    out_dir.mkdir(parents=True, exist_ok=True)

    transcript_path = Path(payload.get("transcript_path", "")).expanduser()
    reply_text = find_last_assistant_text(transcript_path)

    entry = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "hook_event_name": payload.get("hook_event_name"),
        "session_id": payload.get("session_id"),
        "cwd": payload.get("cwd"),
        "transcript_path": str(transcript_path) if transcript_path else None,
        "reply": reply_text,
        "reply_found": reply_text is not None,
        "stop_hook_active": payload.get("stop_hook_active"),
    }

    with (out_dir / "responses.jsonl").open("a", encoding="utf-8") as handle:
        handle.write(json.dumps(entry, ensure_ascii=True) + "\n")

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
