#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
版本历史查看工具
用于查看和管理GUI客户端的版本历史记录
"""

import json
import argparse
from pathlib import Path
from datetime import datetime

PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent


def load_version_history():
    """加载版本历史"""
    version_file = PROJECT_ROOT / 'version_history.json'
    if not version_file.exists():
        return []
    
    with open(version_file, 'r', encoding='utf-8') as f:
        return json.load(f)


def display_version_list(limit: int = 10):
    """显示版本列表"""
    history = load_version_history()
    
    if not history:
        print("📭 暂无版本历史记录")
        return
    
    print("=" * 80)
    print(f"📦 GUI客户端版本历史 (共 {len(history)} 个版本)")
    print("=" * 80)
    
    for i, record in enumerate(history[:limit], 1):
        version = record.get('version', 'Unknown')
        update_type = record.get('update_type', 'unknown').upper()
        author = record.get('author', 'Unknown')
        release_time = record.get('release_time', 'Unknown')
        content = record.get('content', '')[:60]
        
        print(f"\n{i}. v{version} [{update_type}]")
        print(f"   👤 作者: {author}")
        print(f"   📅 时间: {release_time}")
        print(f"   📝 内容: {content}{'...' if len(record.get('content', '')) > 60 else ''}")
        
        stats = record.get('stats', {})
        if stats:
            print(f"   📊 变更: {stats.get('files_changed', 0)} 文件, "
                  f"+{stats.get('lines_added', 0)}/-{stats.get('lines_deleted', 0)} 行")
    
    if len(history) > limit:
        print(f"\n... 还有 {len(history) - limit} 个历史版本")
    
    print("\n" + "=" * 80)


def display_version_detail(version: str):
    """显示特定版本的详细信息"""
    history = load_version_history()
    
    for record in history:
        if record.get('version') == version:
            print("=" * 80)
            print(f"📦 GUI客户端版本详情: v{version}")
            print("=" * 80)
            print(f"版本号: v{record.get('version')}")
            print(f"更新类型: {record.get('update_type', 'unknown').upper()}")
            print(f"作者: {record.get('author')}")
            print(f"发布时间: {record.get('release_time')}")
            print(f"分支: {record.get('branch')}")
            print(f"提交哈希: {record.get('commit_short_hash')}")
            print(f"\n更新内容:\n{record.get('content')}")
            
            stats = record.get('stats', {})
            if stats:
                print(f"\n提交统计:")
                print(f"  文件变更: {stats.get('files_changed', 0)}")
                print(f"  新增行数: +{stats.get('lines_added', 0)}")
                print(f"  删除行数: -{stats.get('lines_deleted', 0)}")
            
            print("=" * 80)
            return
    
    print(f"❌ 未找到版本: v{version}")


def display_latest_version():
    """显示最新版本"""
    history = load_version_history()
    if not history:
        print("📭 暂无版本历史记录")
        return
    
    latest = history[0]
    print(f"🏷️  最新版本: v{latest.get('version')}")
    print(f"📅 发布时间: {latest.get('release_time')}")
    print(f"👤 发布者: {latest.get('author')}")


def export_changelog(output_file: str = None):
    """导出更新日志（Markdown格式）"""
    history = load_version_history()
    
    if not history:
        print("📭 暂无版本历史记录")
        return
    
    output_file = output_file or (PROJECT_ROOT / 'CHANGELOG.md')
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write("# 水滴GUI客户端更新日志\n\n")
        f.write(f"*自动生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*\n\n")
        
        for record in history:
            version = record.get('version')
            update_type = record.get('update_type', 'patch').upper()
            release_time = record.get('release_time')
            author = record.get('author')
            content = record.get('content', '')
            
            f.write(f"## v{version} - {release_time}\n\n")
            f.write(f"**类型**: {update_type} | **作者**: {author}\n\n")
            f.write(f"{content}\n\n")
            
            stats = record.get('stats', {})
            if stats:
                f.write(f"*变更统计: {stats.get('files_changed', 0)} 文件, "
                       f"+{stats.get('lines_added', 0)}/-{stats.get('lines_deleted', 0)} 行*\n\n")
            
            f.write("---\n\n")
    
    print(f"✅ 更新日志已导出到: {output_file}")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='GUI版本历史查看工具')
    parser.add_argument('--list', '-l', action='store_true', help='显示版本列表')
    parser.add_argument('--limit', type=int, default=10, help='显示数量限制（默认10）')
    parser.add_argument('--detail', '-d', type=str, help='查看特定版本详情')
    parser.add_argument('--latest', action='store_true', help='显示最新版本')
    parser.add_argument('--export', '-e', action='store_true', help='导出更新日志')
    parser.add_argument('--output', '-o', type=str, help='导出文件路径')
    
    args = parser.parse_args()
    
    if args.latest:
        display_latest_version()
    elif args.detail:
        display_version_detail(args.detail)
    elif args.export:
        export_changelog(args.output)
    elif args.list or not any(vars(args).values()):
        display_version_list(args.limit)
    else:
        parser.print_help()


if __name__ == '__main__':
    main()

