#!/usr/bin/env python3
"""PostToolUse hook for Write/Edit — record vault .md touch, invalidate rebuild stamp.

Fail-open. Exits silently (no side effects) unless the written file is a .md file
under the configured vault path.
"""
import os
import sys
from datetime import datetime, timezone

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import config as config_mod
import hook_io
import session_state


def _utc():
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def main():
    cache_dir = os.path.expanduser("~/.cache/graphify")
    try:
        os.makedirs(cache_dir, exist_ok=True)
    except Exception:
        pass

    cfg = config_mod.load_config()
    inp = hook_io.read_input()
    file_path = inp.file_path
    session_id = inp.session_id

    if not file_path:
        return
    if not file_path.endswith(".md"):
        return
    if not file_path.startswith(cfg.vault_path):
        return

    log = os.path.join(cache_dir, "post-tool-use.log")
    session_state.record_touch(session_id, file_path)

    stamp = os.path.join(cache_dir, "vault-rebuild.stamp")
    removed_ok = True
    try:
        os.remove(stamp)
    except FileNotFoundError:
        pass
    except Exception:
        removed_ok = False

    try:
        with open(log, "a") as f:
            if removed_ok:
                f.write(f"[{_utc()}] Invalidated rebuild stamp: {file_path}\n")
            else:
                f.write(f"[{_utc()}] WARN: Could not delete rebuild stamp for {file_path}\n")
    except Exception:
        pass


if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"[post-tool-use-write] error: {e}", file=sys.stderr)
    sys.exit(0)
