#!/usr/bin/env python3
"""SessionEnd hook (split out) — auto-commit + push the memsearch memory store.

Preserves ADR-015 behavior: commit memory/*.md in the dedicated memsearch repo and
push to forgejo.swansoncloud.com/jared/memsearch. The memsearch directory is now a
Config field (memsearch_dir, default ~/.memsearch) instead of a hardcoded absolute
path. 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()
    memsearch_dir = cfg.memsearch_dir

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

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


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