#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""
Git Capture: Extract knowledge from local git history.

Part of the Brain V4 Capture pipeline. Bridges local development activity
into the brain's episodic memory. Handles "installed mode" gracefully.
"""
import subprocess
import os
import re
import logging
from datetime import datetime, timezone, timedelta
from pathlib import Path

log = logging.getLogger("pulse.brain.capture.git")


def is_git_repo(path: Path) -> bool:
    """Check if the path is inside a git repository."""
    try:
        # 'git rev-parse' returns 0 if inside a repo
        res = subprocess.run(
            ["git", "-C", str(path), "rev-parse", "--is-inside-work-tree"],
            capture_output=True, text=True, check=False
        )
        return res.returncode == 0
    except Exception:
        return False


def capture_git_history(days: int = 7, path: Path = None) -> list[dict]:
    """Extract recent commits as episodic memory items.

    Fulfills QR8 P12: Fixes crash in installed mode by checking for repo existence.
    """
    if path is None:
        path = Path.cwd()

    if not is_git_repo(path):
        log.debug("Not a git repository: %s. Skipping git capture.", path)
        return []

    since = (datetime.now(timezone.utc) - timedelta(days=days)).strftime("%Y-%m-%d")
    cmd = [
        "git", "-C", str(path), "log",
        f"--since={since}",
        "--pretty=format:COMMIT:%h|%an|%ai|%s",
        "--shortstat"
    ]

    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=False, encoding="utf-8", errors="replace")
        if result.returncode != 0:
            log.warning("Git log failed: %s", result.stderr)
            return []

        commits = []
        current_commit = None
        
        # Simple parser for the custom format
        for line in result.stdout.splitlines():
            line = line.strip()
            if not line: continue
            
            if line.startswith("COMMIT:"):
                if current_commit:
                    commits.append(current_commit)
                parts = line[7:].split("|")
                if len(parts) >= 4:
                    current_commit = {
                        "type": "CONVERSATIONAL", # Commits are dev interactions
                        "source": "git_capture",
                        "id": f"GIT-{parts[0]}",
                        "agent": parts[1],
                        "timestamp": parts[2],
                        "content": parts[3],
                        "title": f"Git Commit: {parts[3][:60]}",
                        "domain": "engineering",
                        "salience": 0.5,
                        "confidence": 0.9,
                    }
            elif "files changed" in line and current_commit:
                current_commit["metadata"] = {"shortstat": line}
                
        if current_commit:
            commits.append(current_commit)
            
        return commits

    except Exception as e:
        log.error("Failed to capture git history: %s", e)
        return []


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    results = capture_git_history()
    print(f"Captured {len(results)} git commits.")
    for r in results[:3]:
        print(f" - {r['title']}")
