#!/usr/bin/env python3
"""
Git commit helper - auto-generates commit message from changed files
Usage: python3 git_commit.py [--push] [--dry-run]
"""

import subprocess
import sys
import os
from datetime import datetime

REPO_PATH = os.path.expanduser("~/echo-core")

def run(cmd, capture=True):
    result = subprocess.run(cmd, shell=True, cwd=REPO_PATH, 
                          capture_output=capture, text=True)
    return result.stdout.strip() if capture else result.returncode

def get_status():
    """Get git status summary"""
    status = run("git status --porcelain")
    if not status:
        return None, []
    
    files = []
    for line in status.split('\n'):
        if line.strip():
            status_code = line[:2]
            filename = line[3:]
            files.append((status_code.strip(), filename))
    return status, files

def generate_message(files):
    """Generate commit message from changed files"""
    # Group by directory/type
    areas = set()
    for _, f in files:
        if '/' in f:
            areas.add(f.split('/')[0])
        else:
            areas.add('root')
    
    # Count changes
    added = len([f for s, f in files if 'A' in s or '?' in s])
    modified = len([f for s, f in files if 'M' in s])
    deleted = len([f for s, f in files if 'D' in s])
    
    parts = []
    if added: parts.append(f"+{added}")
    if modified: parts.append(f"~{modified}")
    if deleted: parts.append(f"-{deleted}")
    
    change_summary = " ".join(parts) if parts else "changes"
    area_list = ", ".join(sorted(areas)[:3])
    if len(areas) > 3:
        area_list += f" +{len(areas)-3} more"
    
    return f"Update {area_list} ({change_summary})"

def main():
    dry_run = "--dry-run" in sys.argv
    push = "--push" in sys.argv
    
    status, files = get_status()
    
    if not status:
        print('{"status": "clean", "message": "Nothing to commit"}')
        return 0
    
    print(f"Files changed: {len(files)}")
    for s, f in files[:10]:
        print(f"  [{s}] {f}")
    if len(files) > 10:
        print(f"  ... and {len(files)-10} more")
    
    message = generate_message(files)
    print(f"\nCommit message: {message}")
    
    if dry_run:
        print("\n[DRY RUN - no changes made]")
        return 0
    
    # Stage all and commit
    run("git add -A", capture=False)
    result = run(f'git commit -m "{message}"')
    print(f"\n{result}")
    
    if push:
        print("\nPushing...")
        push_result = run("git push 2>&1")
        print(push_result)
    
    return 0

if __name__ == "__main__":
    sys.exit(main())
