# -*- coding: utf-8 -*-
"""
システム更新自動化スクリプト
=================================

概要:
    開発環境で使用されるパッケージマネージャーの一括更新を行うPythonスクリプト。
    brew（macOS）とpip（Python）のパッケージを自動更新します。

機能:
    - Homebrew パッケージの更新
    - Python pip パッケージの一括更新
    - 古くなったパッケージの自動検出・更新
    - 特定パッケージの更新除外機能

使用方法:
    python update.py

注意事項:
    - macOSでHomebrewがインストールされている環境で使用してください
    - 管理者権限が必要な場合があります
    - PyGObjectは互換性の問題で更新対象から除外されています

作成者: 中田康史 (Yasufumi Nakata)
最終更新: 2025年
"""

import subprocess
import sys
import time

def run_command(command, description):
    """
    コマンドを実行し、結果を表示する関数

    Args:
        command (list): 実行するコマンドのリスト
        description (str): コマンドの説明

    Returns:
        subprocess.CompletedProcess: コマンドの実行結果
    """
    print(f"\n🔄 {description}")
    print("-" * 50)

    try:
        result = subprocess.run(command, capture_output=True, text=True, check=True)
        if result.stdout:
            print(result.stdout)
        return result
    except subprocess.CalledProcessError as e:
        print(f"❌ エラーが発生しました: {e}")
        if e.stderr:
            print(f"エラーメッセージ: {e.stderr}")
        return None
    except FileNotFoundError:
        print(f"❌ コマンドが見つかりません: {command[0]}")
        print(f"   {command[0]} がインストールされているか確認してください。")
        return None

def update_homebrew():
    """Homebrewパッケージの更新"""
    print("\n🍺 Homebrew パッケージの更新を開始...")

    # brew updateで最新情報を取得
    result = run_command(["brew", "update"], "パッケージ情報の更新")
    if result is None:
        return False

    # brew upgradeで実際の更新を実行
    result = run_command(["brew", "upgrade"], "インストール済みパッケージの更新")
    if result is None:
        return False

    print("✅ Homebrewパッケージの更新が完了しました。")
    return True

def update_pip_packages():
    """Python pipパッケージの更新"""
    print("\n🐍 Python pip パッケージの更新を開始...")

    # 古いパッケージのリストを取得
    print("📋 古くなったパッケージを確認中...")
    result = run_command(["pip", "list", "--outdated"], "古いパッケージの一覧表示")
    if result is None:
        return False

    # 更新対象パッケージを取得
    update_result = subprocess.run(["pip", "list", "--outdated"],
                                 capture_output=True, text=True)

    if update_result.returncode != 0:
        print("❌ パッケージリストの取得に失敗しました。")
        return False

    # パッケージリストを解析
    lines = update_result.stdout.strip().split('\n')
    if len(lines) <= 2:  # ヘッダー行のみの場合
        print("✅ すべてのパッケージが最新です。")
        return True

    # 除外するパッケージのリスト
    excluded_packages = {"PyGObject", "pyobjc", "pyobjc-core"}

    updated_count = 0
    failed_count = 0

    # 各パッケージを更新
    for line in lines[2:]:  # ヘッダー行をスキップ
        if line.strip():
            parts = line.split()
            if len(parts) >= 1:
                package_name = parts[0]

                if package_name in excluded_packages:
                    print(f"⏭️  {package_name} は除外されています。")
                    continue

                print(f"\n📦 {package_name} を更新中...")
                result = run_command(["pip", "install", "-U", package_name],
                                   f"{package_name} の更新")

                if result is not None:
                    updated_count += 1
                    print(f"✅ {package_name} の更新が完了しました。")
                else:
                    failed_count += 1
                    print(f"❌ {package_name} の更新に失敗しました。")

                # 連続実行の負荷軽減のため少し待機
                time.sleep(0.5)

    print(f"\n📊 更新結果:")
    print(f"   成功: {updated_count} パッケージ")
    print(f"   失敗: {failed_count} パッケージ")
    print("✅ Python pipパッケージの更新が完了しました。")

    return True

def main():
    """メイン処理"""
    print("🚀 システム更新スクリプトを開始します...")
    print("=" * 60)
    print("開発環境のパッケージマネージャーを一括更新します。")
    print("対象: Homebrew (macOS), pip (Python)")
    print("=" * 60)

    start_time = time.time()
    success_count = 0
    total_tasks = 2

    # Homebrewの更新
    if update_homebrew():
        success_count += 1

    # pipパッケージの更新
    if update_pip_packages():
        success_count += 1

    # 結果サマリー
    end_time = time.time()
    elapsed_time = int(end_time - start_time)

    print("\n" + "=" * 60)
    print("🎉 システム更新スクリプトが完了しました！")
    print(f"📊 実行結果: {success_count}/{total_tasks} タスクが成功")
    print(f"⏱️  実行時間: {elapsed_time}秒")

    if success_count == total_tasks:
        print("✅ すべての更新が正常に完了しました。")
        return 0
    else:
        print("⚠️  一部の更新でエラーが発生しました。ログを確認してください。")
        return 1

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