#!/usr/bin/env python3
"""SessionEnd hook — auto-commit + push the SecondBrain vault.

Step 5b automation: commit vault content and push to
forgejo.swansoncloud.com/jared/SecondBrain. Mirrors memsearch_sync.py.
Must run AFTER session_end.py so the daily journal note that hook writes is
included in the commit. The disposable graphify-out/ index is excluded via the
vault's .gitignore. Fail-open; must never disrupt session shutdown.
"""
import os
import sys
import subprocess
from datetime import datetime

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


def main():
    cfg = config_mod.load_config()
    vault_dir = cfg.vault_path

    if not os.path.isdir(os.path.join(vault_dir, ".git")):
        return

    devnull = subprocess.DEVNULL
    subprocess.run(["git", "-C", vault_dir, "add", "-A"], stdout=devnull, stderr=devnull)
    staged = subprocess.run(
        ["git", "-C", vault_dir, "diff", "--cached", "--quiet"],
        stdout=devnull, stderr=devnull,
    )
    if staged.returncode != 0:
        date_str = datetime.now().strftime("%Y-%m-%d")
        subprocess.run(
            ["git", "-C", vault_dir, "commit", "-m", f"vault: session notes {date_str}"],
            stdout=devnull, stderr=devnull,
        )
        print("[session-end] vault committed")
    subprocess.run(
        ["timeout", "30", "git", "-C", vault_dir, "push", "--quiet", "origin", "main"],
        stdout=devnull, stderr=devnull,
    )


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