# 🔍 WCG - Watch Commits for Git

[![Python Version](https://img.shields.io/badge/python-3.12%2B-blue.svg)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

**WCG** is an automated GitHub commit monitoring and summarization tool that intelligently analyzes and summarizes code changes using LLM technology.

## ✨ Features

- 🤖 **Intelligent Summarization**: Automatically generate commit summaries using LLM (OpenAI-compatible API)
- ✨ **Custom Prompts**: Fully customizable system and user prompts to control AI behavior and output format
- 📊 **Categorized Organization**: Display changes categorized by additions, modifications, and deletions
- 🔗 **PR Association**: Automatically associate Pull Requests and provide file change links
- ⏰ **Scheduled Execution**: Automatically process commits from the last 24 hours at a scheduled time (default: 10:00 AM)
- 📢 **Webhook Notifications**: Support multiple webhook formats (Generic, Slack, Discord, Feishu/Lark)
- 💾 **Local Storage**: Save summaries locally organized by date
- 🌐 **Web Configuration Interface**: Manage configuration with a user-friendly Web UI that automatically saves changes
- 📦 **Easy Deployment**: Packaged with `uv` and published to PyPI

## 📦 Installation

### Install from PyPI

```bash
pip install wcg
```

### Install from Source

```bash
# Clone the repository
git clone https://github.com/wZuck/WCG.git
cd WCG

# Install using uv
uv pip install -e .
```

## 🚀 Quick Start

### 1. Configuration (Option A: Manual Configuration)

Copy the example configuration file:

```bash
mkdir -p config
cp config/config.example.yaml config/config.yaml
```

Edit `config/config.yaml` and fill in your configuration:

```yaml
llm:
  api_url: "https://api.openai.com/v1"
  api_key: "your-api-key-here"
  model: "gpt-3.5-turbo"

github_token: "your-github-token-here"

repositories:
  - name: "owner/repository"
    branch: "main"
    webhook_url: "https://your-webhook-url.com"

schedule_time: "10:00"
timezone: "Asia/Shanghai"  # UTC+8 China Standard Time
summary_dir: "summaries"
```

**Note**: `schedule_time` uses the configured timezone (default `Asia/Shanghai` UTC+8). If the server time is inaccurate, set `timezone` to the target timezone, and the program will execute according to that timezone.

### 2. Configuration (Option B: Web Interface - Recommended)

Start the web configuration server:

```bash
wcg-web
```

Visit http://localhost:5000 in your browser to configure WCG through the web interface. **All changes made through the web interface are automatically saved to the configuration file.**

### 3. Run

#### Start Scheduled Task

```bash
wcg start
```

#### Run Once Immediately (Testing)

```bash
wcg run-once
```

#### Use Custom Configuration File

```bash
wcg start --config /path/to/config.yaml
```

#### Set Log Level

```bash
wcg start --log-level DEBUG
```

## 📖 Usage

### Command Line Tools

WCG provides two command line tools:

1. **wcg** - Main program for starting scheduled tasks
   - `wcg start` - Start the scheduler
   - `wcg run-once` - Execute once immediately (for testing)

2. **wcg-web** - Web configuration interface
   - After starting, visit http://localhost:5000 for configuration management
   - All configuration changes are automatically saved to `config/config.yaml`

### Configuration Guide

#### LLM Configuration

- **api_url**: LLM API endpoint (supports OpenAI-compatible interfaces)
- **api_key**: API key
- **model**: Model name to use
- **system_prompt** (optional): Custom system prompt that defines the AI assistant's role and behavior
  - Default: "你是一个专业的技术文档编写助手，擅长总结代码变更。请使用中文回答，并以清晰的markdown格式组织内容。"
  - You can customize this to change the assistant's personality, language, or output style
- **user_prompt_template** (optional): Custom template for the user prompt sent to the LLM
  - Available placeholders: `{repo_name}`, `{branch}`, `{organized}`
  - Default template includes instructions for organizing changes by type (new/modified/deleted) and module
  - You can customize this to change how the commit data is presented and what kind of summary you want

**Example custom prompts in config.yaml:**

```yaml
llm:
  api_url: "https://api.openai.com/v1"
  api_key: "your-api-key-here"
  model: "gpt-3.5-turbo"
  system_prompt: "You are a technical writer specialized in creating clear, concise commit summaries in English."
  user_prompt_template: |
    Summarize the following commits for {repo_name} (branch: {branch}):
    
    Changes in the last 24 hours:
    {organized}
    
    Please create a brief summary highlighting the main changes.
```

#### GitHub Configuration

- **github_token**: GitHub Personal Access Token
  - A valid token must be provided, otherwise you will get "401 Bad credentials" error
  - Steps to create a token:
    1. Visit https://github.com/settings/tokens
    2. Click "Generate new token (classic)"
    3. Fill in the description and select `repo` permission (full repository access)
    4. Copy the token immediately after generation (it will only be shown once)
    5. Paste the token into the `github_token` field in `config.yaml`
  - `repo` permission is required to access private repositories
  - Public repositories also need a token to avoid API rate limits
  - Ensure the token is not expired and has sufficient permissions

#### Repository Configuration

Each repository configuration includes:
- **name**: Repository name (format: `owner/repo`)
- **branch**: Branch to monitor
- **webhook_url**: Webhook URL to receive summaries

#### Other Settings

- **schedule_time**: Scheduled execution time (24-hour format: `HH:MM`)
- **timezone**: Timezone setting (default: `Asia/Shanghai` UTC+8)
  - Use standard IANA timezone names, such as `Asia/Shanghai`, `America/New_York`, etc.
  - If server time is inaccurate, set this to specify the target timezone
  - The program will execute tasks at `schedule_time` according to the specified timezone
- **summary_dir**: Local directory to save summaries

### Output Format

Generated summaries use Markdown format and include:

- 📝 **Title**: Repository name and branch
- 🆕 **New Features**: Added files and features
- 🔧 **Code Changes**: Modified files and content
- 🗑️ **Deletions**: Deleted files
- 🔗 **PR Links**: Links to related Pull Requests

### Webhook Support

WCG supports multiple webhook formats:

- **Generic**: Standard JSON payload
- **Slack**: Slack-compatible message format
- **Discord**: Discord embed message format
- **Feishu/Lark**: Feishu/Lark message card format

### Local Storage

Summary files are saved with the following structure:

```
summaries/
├── 2024-01/
│   ├── 01/
│   │   └── owner-repo-main.md
│   ├── 02/
│   │   └── owner-repo-main.md
```

## 🔧 Development

### Environment Setup

```bash
# Install development dependencies
uv pip install -e ".[dev]"

# Run tests
pytest

# Format code
ruff format .

# Lint code
ruff check .
```

### Project Structure

```
WCG/
├── src/wcg/
│   ├── __init__.py          # Package initialization
│   ├── cli.py               # Command line interface
│   ├── config.py            # Configuration management
│   ├── github_client.py     # GitHub API client
│   ├── summarizer.py        # LLM summarizer
│   ├── notifier.py          # Webhook notifier
│   ├── storage.py           # Local storage
│   ├── scheduler.py         # Task scheduler
│   ├── web.py               # Web interface
│   └── templates/
│       └── index.html       # Web UI template
├── config/
│   └── config.example.yaml  # Configuration example
├── summaries/               # Summary output directory
├── tests/                   # Test files
├── pyproject.toml          # Project configuration
└── README.md               # This file
```

## 🔍 Troubleshooting

### Common Errors and Solutions

#### 1. "401 Bad credentials" Error

**Error Message**: `Error fetching commits from xxx/xxx/main: 401 {"message": "Bad credentials"...}`

**Causes**:
- GitHub token not configured or empty
- Token is invalid or expired
- Token lacks necessary permissions

**Solutions**:
1. Check if the `github_token` field in `config.yaml` is correctly configured
2. Ensure the token is not the default value `your-github-token-here`
3. Visit https://github.com/settings/tokens to create a new token
4. Select `repo` permission (full repository access)
5. Copy the generated token and update it in the configuration file

#### 2. "403 Forbidden" Error

**Causes**:
- Token lacks permission to access a specific repository
- GitHub API rate limit reached
- Repository does not exist or no access permission

**Solutions**:
1. Ensure the token has `repo` permission
2. Check if you can access the target repository
3. If it's a rate limit issue, wait for some time and retry
4. Using an authenticated token provides higher rate limits (5000 requests/hour vs 60 requests/hour)

#### 3. "404 Not Found" Error

**Causes**:
- Repository name format is incorrect
- Branch name is incorrect
- Repository does not exist or is private without access permission

**Solutions**:
1. Check if the repository name format is correct (format: `owner/repo`)
2. Confirm the branch name is correct (e.g., `main` or `master`)
3. Ensure you have permission to access the repository

## 📝 License

MIT License

## 🤝 Contributing

Issues and Pull Requests are welcome!

## 📮 Contact

If you have any questions or suggestions, please submit an [Issue](https://github.com/wZuck/WCG/issues).
