#!python3
# coding=utf-8

from openai import OpenAI
import fire
import httpx
import subprocess
import sys

_VERSION_ = "1.0.0"
_MODEL_ = "doubao-seed-2-0-code-preview-260215"
_BASE_URL_ = "https://ark.cn-beijing.volces.com/api/v3"
_API_KEY_ = "0fb5c683-9002-4bca-9811-b81f46d07e9c"

# 初始化OpenAI客户端
client = OpenAI(
    base_url=_BASE_URL_,
    api_key=_API_KEY_,
    http_client=httpx.Client(verify=False, timeout=60.0),
)

prompt_zh = """你是一位专业的 Pull Request 标题生成助手。请根据提供的 git commit 历史，生成简洁、清晰的 PR 标题。

<requirements>
1. 使用中文描述
2. 标题要简洁明了，概括主要变更内容
3. 突出核心功能或修复的问题
4. 不要包含 commit hash 或技术细节
5. 长度控制在 50 字符以内
6. 只返回 PR 标题，不要添加任何解释或前缀
</requirements>

<examples>
添加用户头像上传功能
修复首页加载性能问题
优化数据库查询和缓存机制
重构组件库架构并更新文档
</examples>"""

prompt_en = """You are a professional Pull Request title generator. Generate concise and clear PR titles based on the provided git commit history.

<requirements>
1. Use English for descriptions
2. Keep the title concise and summarize the main changes
3. Highlight the core functionality or fixes
4. Do not include commit hashes or technical details
5. Keep length under 50 characters
6. Return only the PR title without any explanations or prefixes
</requirements>

<examples>
Add user avatar upload feature
Fix homepage loading performance issue
Optimize database query and caching
Refactor component library and update docs
</examples>"""


def get_base_branch():
    """
    获取基准分支（main 或 master）
    :return: 基准分支名称
    """
    try:
        # 检查是否存在 main 分支
        result = subprocess.run(
            ['git', 'rev-parse', '--verify', 'main'],
            capture_output=True,
            text=True
        )
        if result.returncode == 0:
            return 'main'
        
        # 检查是否存在 master 分支
        result = subprocess.run(
            ['git', 'rev-parse', '--verify', 'master'],
            capture_output=True,
            text=True
        )
        if result.returncode == 0:
            return 'master'
        
        # 检查远程 origin/main
        result = subprocess.run(
            ['git', 'rev-parse', '--verify', 'origin/main'],
            capture_output=True,
            text=True
        )
        if result.returncode == 0:
            return 'origin/main'
        
        # 检查远程 origin/master
        result = subprocess.run(
            ['git', 'rev-parse', '--verify', 'origin/master'],
            capture_output=True,
            text=True
        )
        if result.returncode == 0:
            return 'origin/master'
        
        return None
    except Exception as e:
        print(f"检查基准分支失败: {e}")
        return None


def get_current_branch():
    """
    获取当前分支名称
    :return: 当前分支名称
    """
    try:
        result = subprocess.run(
            ['git', 'branch', '--show-current'],
            capture_output=True,
            text=True,
            check=True
        )
        return result.stdout.strip()
    except subprocess.CalledProcessError as e:
        print(f"获取当前分支失败: {e}")
        return None


def get_commits_diff(base_branch):
    """
    获取当前分支相比基准分支的 commit 列表
    :param base_branch: 基准分支名称
    :return: commit 历史信息
    """
    try:
        # 获取 commit 列表（格式：hash + message）
        # 使用 --no-pager 禁用分页器
        result = subprocess.run(
            ['git', '--no-pager', 'log', f'{base_branch}..HEAD', '--pretty=format:%h - %s'],
            capture_output=True,
            text=True,
            check=True
        )
        
        if not result.stdout.strip():
            print(f"当前分支与 {base_branch} 没有差异")
            return None
        
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"获取 commit 差异失败: {e}")
        return None


def generate_pr_title(commits, language='en'):
    """
    使用 AI API 生成 PR 标题
    :param commits: commit 历史信息
    :param language: 语言选择，'zh' 或 'en'，默认 'en'
    :return: 生成的 PR 标题
    """
    try:
        # 根据语言选择prompt和提示文本
        if language == 'zh':
            prompt = prompt_zh
            instruction = "请根据以下 commit 历史生成 PR 标题："
        else:
            prompt = prompt_en
            instruction = "Please generate a PR title based on the following commit history:"
        
        user_message = f"""{instruction}

<commits>
{commits}
</commits>"""
        
        completion = client.chat.completions.create(
            model=_MODEL_,
            messages=[
                {"role": "system", "content": prompt},
                {"role": "user", "content": user_message},
            ],
        )
        return completion.choices[0].message.content.strip()
    except Exception as e:
        print(f"生成 PR 标题失败: {str(e)}")
        return None


def main(base=None, lang='en', copy=False):
    """
    主函数：生成 Pull Request 标题
    :param base: 基准分支名称，默认自动检测 main/master
    :param lang: PR 标题语言，'zh' 或 'en'，默认 'en'
    :param copy: 是否复制到剪贴板，默认 False
    """
    # 获取当前分支
    current_branch = get_current_branch()
    if not current_branch:
        return
    
    print(f"当前分支: {current_branch}")
    
    # 确定基准分支
    if base:
        base_branch = base
    else:
        base_branch = get_base_branch()
        if not base_branch:
            print("未找到基准分支（main/master），请使用 --base 参数指定")
            return
    
    print(f"基准分支: {base_branch}")
    print(f"正在对比 {base_branch}..{current_branch}...\n")
    
    # 获取 commit 差异
    commits = get_commits_diff(base_branch)
    if not commits:
        return
    
    print("提交历史：")
    print("="*50)
    print(commits)
    print("="*50 + "\n")
    
    print("正在生成 PR 标题...")
    
    # 生成 PR 标题
    pr_title = generate_pr_title(commits, lang)
    if not pr_title:
        return
    
    print("\n" + "="*50)
    print("生成的 PR 标题：")
    print("="*50)
    print(pr_title)
    print("="*50 + "\n")
    
    # 复制到剪贴板
    if copy:
        try:
            subprocess.run(
                ['pbcopy'],
                input=pr_title.encode('utf-8'),
                check=True
            )
            print("✅ 已复制到剪贴板！")
        except (subprocess.CalledProcessError, FileNotFoundError):
            print("⚠️  复制到剪贴板失败（仅支持 macOS）")


if __name__ == '__main__':
    fire.Fire(main)
