"""bucket 命令 - S3 Bucket 级别操作

覆盖 boto3 S3 的所有 bucket 级别操作:
list, create, delete, head, versioning, lifecycle, cors,
policy, website, encryption, replication, acl, tagging,
logging, notification, public_access_block, accelerate
"""
import json
import sys
from typing import Optional

from rich.table import Table
from rich.console import Console
from rich.panel import Panel
from botocore.exceptions import ClientError

from .client import get_s3_client
from .utils import (
    console, err_console, format_size, format_datetime,
    print_json, handle_error
)


class Bucket:
    """S3 Bucket 管理命令"""

    # ── 基础操作 ────────────────────────────────────────────────

    def list(self, format: str = "table") -> None:
        """列出所有 bucket

        Args:
            format: 输出格式，table 或 json（默认 table）

        示例:
            s3c bucket list
            s3c -c prod bucket list --format json
        """
        try:
            s3 = get_s3_client()
            response = s3.list_buckets()
            buckets = response.get("Buckets", [])
        except Exception as e:
            handle_error(e, "list buckets")

        if format == "json":
            print_json([
                {"Name": b["Name"], "CreationDate": b["CreationDate"]}
                for b in buckets
            ])
            return

        table = Table(title=f"Buckets ({len(buckets)})", show_lines=False)
        table.add_column("名称", style="cyan", min_width=20)
        table.add_column("创建时间", min_width=20)

        for b in buckets:
            table.add_row(b["Name"], format_datetime(b.get("CreationDate")))

        console.print(table)

    def create(
        self,
        bucket: str,
        region: Optional[str] = None,
        private: bool = True,
    ) -> None:
        """创建 bucket

        Args:
            bucket:  Bucket 名称
            region:  区域（默认使用配置中的区域）
            private: 是否设为私有（默认 True）

        示例:
            s3c bucket create my-bucket
            s3c bucket create my-bucket --region us-west-2
        """
        try:
            s3 = get_s3_client()
            kwargs: dict = {"Bucket": bucket}

            # us-east-1 不能指定 LocationConstraint，否则报错
            if region and region != "us-east-1":
                kwargs["CreateBucketConfiguration"] = {"LocationConstraint": region}

            if not private:
                kwargs["ObjectOwnership"] = "BucketOwnerPreferred"

            s3.create_bucket(**kwargs)
            console.print(f"[green]✓[/green] Bucket [cyan]{bucket}[/cyan] 创建成功")
        except Exception as e:
            handle_error(e, "create bucket")

    def delete(self, bucket: str, force: bool = False) -> None:
        """删除 bucket

        Args:
            bucket: Bucket 名称
            force:  强制删除（会先清空所有对象和版本，默认 False）

        示例:
            s3c bucket delete my-bucket
            s3c bucket delete my-bucket --force
        """
        try:
            s3 = get_s3_client()

            if force:
                # 先删除所有对象版本和删除标记
                self._empty_bucket(s3, bucket)

            s3.delete_bucket(Bucket=bucket)
            console.print(f"[green]✓[/green] Bucket [cyan]{bucket}[/cyan] 已删除")
        except Exception as e:
            handle_error(e, "delete bucket")

    def _empty_bucket(self, s3, bucket: str) -> None:
        """清空 bucket 中的所有对象和版本"""
        paginator = s3.get_paginator("list_object_versions")
        for page in paginator.paginate(Bucket=bucket):
            objects_to_delete = []
            for version in page.get("Versions", []):
                objects_to_delete.append(
                    {"Key": version["Key"], "VersionId": version["VersionId"]}
                )
            for marker in page.get("DeleteMarkers", []):
                objects_to_delete.append(
                    {"Key": marker["Key"], "VersionId": marker["VersionId"]}
                )
            if objects_to_delete:
                s3.delete_objects(
                    Bucket=bucket, Delete={"Objects": objects_to_delete}
                )

    def head(self, bucket: str) -> None:
        """查看 bucket 元数据信息

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket head my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.head_bucket(Bucket=bucket)
            meta = response.get("ResponseMetadata", {})
            console.print(Panel(
                f"[cyan]Bucket:[/cyan] {bucket}\n"
                f"[cyan]Region:[/cyan] {meta.get('HTTPHeaders', {}).get('x-amz-bucket-region', '-')}\n"
                f"[cyan]HTTP 状态:[/cyan] {meta.get('HTTPStatusCode', '-')}",
                title="Bucket 信息",
                expand=False,
            ))
        except Exception as e:
            handle_error(e, "head bucket")

    # ── 版本控制 ─────────────────────────────────────────────────

    def versioning_get(self, bucket: str) -> None:
        """查看 bucket 版本控制状态

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket versioning-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_versioning(Bucket=bucket)
            status = response.get("Status", "Suspended")
            mfa = response.get("MFADelete", "Disabled")
            console.print(f"版本控制: [bold]{status}[/bold]  MFA 删除: {mfa}")
        except Exception as e:
            handle_error(e, "get versioning")

    def versioning_enable(self, bucket: str) -> None:
        """启用 bucket 版本控制

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket versioning-enable my-bucket
        """
        try:
            s3 = get_s3_client()
            s3.put_bucket_versioning(
                Bucket=bucket,
                VersioningConfiguration={"Status": "Enabled"},
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 版本控制已启用")
        except Exception as e:
            handle_error(e, "enable versioning")

    def versioning_suspend(self, bucket: str) -> None:
        """暂停 bucket 版本控制

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket versioning-suspend my-bucket
        """
        try:
            s3 = get_s3_client()
            s3.put_bucket_versioning(
                Bucket=bucket,
                VersioningConfiguration={"Status": "Suspended"},
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 版本控制已暂停")
        except Exception as e:
            handle_error(e, "suspend versioning")

    # ── 生命周期 ─────────────────────────────────────────────────

    def lifecycle_get(self, bucket: str) -> None:
        """查看 bucket 生命周期配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket lifecycle-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_lifecycle_configuration(Bucket=bucket)
            print_json(response.get("Rules", []))
        except ClientError as e:
            if e.response["Error"]["Code"] == "NoSuchLifecycleConfiguration":
                console.print(f"[yellow]未配置生命周期规则[/yellow]")
            else:
                handle_error(e, "get lifecycle")

    def lifecycle_put(self, bucket: str, rules_file: str) -> None:
        """设置 bucket 生命周期配置

        Args:
            bucket:     Bucket 名称
            rules_file: 包含生命周期规则的 JSON 文件路径

        示例:
            s3c bucket lifecycle-put my-bucket rules.json
        """
        try:
            with open(rules_file, "r", encoding="utf-8") as f:
                rules = json.load(f)
            s3 = get_s3_client()
            s3.put_bucket_lifecycle_configuration(
                Bucket=bucket,
                LifecycleConfiguration={"Rules": rules},
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 生命周期规则已更新")
        except Exception as e:
            handle_error(e, "put lifecycle")

    def lifecycle_delete(self, bucket: str) -> None:
        """删除 bucket 生命周期配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket lifecycle-delete my-bucket
        """
        try:
            s3 = get_s3_client()
            s3.delete_bucket_lifecycle(Bucket=bucket)
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 生命周期规则已删除")
        except Exception as e:
            handle_error(e, "delete lifecycle")

    # ── CORS ─────────────────────────────────────────────────────

    def cors_get(self, bucket: str) -> None:
        """查看 bucket CORS 配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket cors-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_cors(Bucket=bucket)
            print_json(response.get("CORSRules", []))
        except ClientError as e:
            if e.response["Error"]["Code"] == "NoSuchCORSConfiguration":
                console.print("[yellow]未配置 CORS 规则[/yellow]")
            else:
                handle_error(e, "get cors")

    def cors_put(self, bucket: str, rules_file: str) -> None:
        """设置 bucket CORS 配置

        Args:
            bucket:     Bucket 名称
            rules_file: 包含 CORS 规则的 JSON 文件路径

        示例:
            s3c bucket cors-put my-bucket cors.json
        """
        try:
            with open(rules_file, "r", encoding="utf-8") as f:
                rules = json.load(f)
            s3 = get_s3_client()
            s3.put_bucket_cors(
                Bucket=bucket,
                CORSConfiguration={"CORSRules": rules},
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] CORS 规则已更新")
        except Exception as e:
            handle_error(e, "put cors")

    def cors_delete(self, bucket: str) -> None:
        """删除 bucket CORS 配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket cors-delete my-bucket
        """
        try:
            s3 = get_s3_client()
            s3.delete_bucket_cors(Bucket=bucket)
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] CORS 规则已删除")
        except Exception as e:
            handle_error(e, "delete cors")

    # ── Bucket Policy ─────────────────────────────────────────────

    def policy_get(self, bucket: str) -> None:
        """查看 bucket 访问策略

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket policy-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_policy(Bucket=bucket)
            policy = json.loads(response["Policy"])
            print_json(policy)
        except ClientError as e:
            if e.response["Error"]["Code"] == "NoSuchBucketPolicy":
                console.print("[yellow]未配置 Bucket Policy[/yellow]")
            else:
                handle_error(e, "get policy")

    def policy_put(self, bucket: str, policy_file: str) -> None:
        """设置 bucket 访问策略

        Args:
            bucket:      Bucket 名称
            policy_file: 包含 Policy JSON 的文件路径

        示例:
            s3c bucket policy-put my-bucket policy.json
        """
        try:
            with open(policy_file, "r", encoding="utf-8") as f:
                policy = f.read()
            s3 = get_s3_client()
            s3.put_bucket_policy(Bucket=bucket, Policy=policy)
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] Policy 已更新")
        except Exception as e:
            handle_error(e, "put policy")

    def policy_delete(self, bucket: str) -> None:
        """删除 bucket 访问策略

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket policy-delete my-bucket
        """
        try:
            s3 = get_s3_client()
            s3.delete_bucket_policy(Bucket=bucket)
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] Policy 已删除")
        except Exception as e:
            handle_error(e, "delete policy")

    # ── 静态网站托管 ──────────────────────────────────────────────

    def website_get(self, bucket: str) -> None:
        """查看 bucket 静态网站托管配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket website-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_website(Bucket=bucket)
            response.pop("ResponseMetadata", None)
            print_json(response)
        except ClientError as e:
            if e.response["Error"]["Code"] == "NoSuchWebsiteConfiguration":
                console.print("[yellow]未配置静态网站托管[/yellow]")
            else:
                handle_error(e, "get website")

    def website_put(self, bucket: str, index: str = "index.html", error: str = "error.html") -> None:
        """启用 bucket 静态网站托管

        Args:
            bucket: Bucket 名称
            index:  索引文档（默认 index.html）
            error:  错误文档（默认 error.html）

        示例:
            s3c bucket website-put my-bucket
            s3c bucket website-put my-bucket --index home.html --error 404.html
        """
        try:
            s3 = get_s3_client()
            s3.put_bucket_website(
                Bucket=bucket,
                WebsiteConfiguration={
                    "IndexDocument": {"Suffix": index},
                    "ErrorDocument": {"Key": error},
                },
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 静态网站托管已启用")
        except Exception as e:
            handle_error(e, "put website")

    def website_delete(self, bucket: str) -> None:
        """删除 bucket 静态网站托管配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket website-delete my-bucket
        """
        try:
            s3 = get_s3_client()
            s3.delete_bucket_website(Bucket=bucket)
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 静态网站托管已禁用")
        except Exception as e:
            handle_error(e, "delete website")

    # ── 加密 ─────────────────────────────────────────────────────

    def encryption_get(self, bucket: str) -> None:
        """查看 bucket 服务端加密配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket encryption-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_encryption(Bucket=bucket)
            print_json(response.get("ServerSideEncryptionConfiguration", {}))
        except ClientError as e:
            if e.response["Error"]["Code"] == "ServerSideEncryptionConfigurationNotFoundError":
                console.print("[yellow]未配置服务端加密[/yellow]")
            else:
                handle_error(e, "get encryption")

    def encryption_put(self, bucket: str, algorithm: str = "AES256", kms_key: Optional[str] = None) -> None:
        """设置 bucket 服务端加密

        Args:
            bucket:    Bucket 名称
            algorithm: 加密算法，AES256 或 aws:kms（默认 AES256）
            kms_key:   KMS Key ARN（仅 aws:kms 时需要）

        示例:
            s3c bucket encryption-put my-bucket
            s3c bucket encryption-put my-bucket --algorithm aws:kms --kms-key arn:aws:kms:...
        """
        try:
            rule: dict = {"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": algorithm}}
            if kms_key:
                rule["ApplyServerSideEncryptionByDefault"]["KMSMasterKeyID"] = kms_key

            s3 = get_s3_client()
            s3.put_bucket_encryption(
                Bucket=bucket,
                ServerSideEncryptionConfiguration={"Rules": [rule]},
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 加密已配置 ({algorithm})")
        except Exception as e:
            handle_error(e, "put encryption")

    def encryption_delete(self, bucket: str) -> None:
        """删除 bucket 服务端加密配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket encryption-delete my-bucket
        """
        try:
            s3 = get_s3_client()
            s3.delete_bucket_encryption(Bucket=bucket)
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 加密配置已删除")
        except Exception as e:
            handle_error(e, "delete encryption")

    # ── 标签 ─────────────────────────────────────────────────────

    def tagging_get(self, bucket: str) -> None:
        """查看 bucket 标签

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket tagging-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_tagging(Bucket=bucket)
            tags = {t["Key"]: t["Value"] for t in response.get("TagSet", [])}
            print_json(tags)
        except ClientError as e:
            if e.response["Error"]["Code"] == "NoSuchTagSet":
                console.print("[yellow]未设置标签[/yellow]")
            else:
                handle_error(e, "get tagging")

    def tagging_put(self, bucket: str, tags: str) -> None:
        """设置 bucket 标签

        Args:
            bucket: Bucket 名称
            tags:   标签，格式: Key1=Value1,Key2=Value2

        示例:
            s3c bucket tagging-put my-bucket "env=prod,team=ops"
        """
        try:
            tag_set = [
                {"Key": k, "Value": v}
                for item in tags.split(",")
                for k, v in [item.strip().split("=", 1)]
            ]
            s3 = get_s3_client()
            s3.put_bucket_tagging(
                Bucket=bucket,
                Tagging={"TagSet": tag_set},
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 标签已更新")
        except Exception as e:
            handle_error(e, "put tagging")

    def tagging_delete(self, bucket: str) -> None:
        """删除 bucket 所有标签

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket tagging-delete my-bucket
        """
        try:
            s3 = get_s3_client()
            s3.delete_bucket_tagging(Bucket=bucket)
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 标签已删除")
        except Exception as e:
            handle_error(e, "delete tagging")

    # ── 日志 ─────────────────────────────────────────────────────

    def logging_get(self, bucket: str) -> None:
        """查看 bucket 访问日志配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket logging-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_logging(Bucket=bucket)
            log_config = response.get("LoggingEnabled")
            if log_config:
                print_json(log_config)
            else:
                console.print("[yellow]未配置访问日志[/yellow]")
        except Exception as e:
            handle_error(e, "get logging")

    def logging_put(self, bucket: str, target_bucket: str, prefix: str = "logs/") -> None:
        """启用 bucket 访问日志

        Args:
            bucket:        Bucket 名称
            target_bucket: 日志存储目标 bucket
            prefix:        日志文件前缀（默认 logs/）

        示例:
            s3c bucket logging-put my-bucket my-logs-bucket
            s3c bucket logging-put my-bucket my-logs-bucket --prefix access-logs/
        """
        try:
            s3 = get_s3_client()
            s3.put_bucket_logging(
                Bucket=bucket,
                BucketLoggingStatus={
                    "LoggingEnabled": {
                        "TargetBucket": target_bucket,
                        "TargetPrefix": prefix,
                    }
                },
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 访问日志已启用 → {target_bucket}/{prefix}")
        except Exception as e:
            handle_error(e, "put logging")

    # ── ACL ──────────────────────────────────────────────────────

    def acl_get(self, bucket: str) -> None:
        """查看 bucket ACL

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket acl-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_acl(Bucket=bucket)
            response.pop("ResponseMetadata", None)
            print_json(response)
        except Exception as e:
            handle_error(e, "get acl")

    def acl_put(self, bucket: str, acl: str) -> None:
        """设置 bucket ACL

        Args:
            bucket: Bucket 名称
            acl:    ACL 类型: private | public-read | public-read-write |
                    authenticated-read | log-delivery-write

        示例:
            s3c bucket acl-put my-bucket private
            s3c bucket acl-put my-bucket public-read
        """
        valid = {"private", "public-read", "public-read-write",
                 "authenticated-read", "log-delivery-write"}
        if acl not in valid:
            err_console.print(f"无效的 ACL 类型: {acl}\n可选: {', '.join(sorted(valid))}")
            raise SystemExit(1)
        try:
            s3 = get_s3_client()
            s3.put_bucket_acl(Bucket=bucket, ACL=acl)
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] ACL 已设置为 {acl}")
        except Exception as e:
            handle_error(e, "put acl")

    # ── 公共访问阻止 ──────────────────────────────────────────────

    def public_access_get(self, bucket: str) -> None:
        """查看 bucket 公共访问阻止配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket public-access-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_public_access_block(Bucket=bucket)
            print_json(response.get("PublicAccessBlockConfiguration", {}))
        except Exception as e:
            handle_error(e, "get public access block")

    def public_access_put(
        self,
        bucket: str,
        block_public_acls: bool = True,
        ignore_public_acls: bool = True,
        block_public_policy: bool = True,
        restrict_public_buckets: bool = True,
    ) -> None:
        """设置 bucket 公共访问阻止

        Args:
            bucket:                 Bucket 名称
            block_public_acls:      阻止公共 ACL（默认 True）
            ignore_public_acls:     忽略公共 ACL（默认 True）
            block_public_policy:    阻止公共 Policy（默认 True）
            restrict_public_buckets: 限制公共 bucket（默认 True）

        示例:
            s3c bucket public-access-put my-bucket
            s3c bucket public-access-put my-bucket --no-block-public-acls
        """
        try:
            s3 = get_s3_client()
            s3.put_public_access_block(
                Bucket=bucket,
                PublicAccessBlockConfiguration={
                    "BlockPublicAcls": block_public_acls,
                    "IgnorePublicAcls": ignore_public_acls,
                    "BlockPublicPolicy": block_public_policy,
                    "RestrictPublicBuckets": restrict_public_buckets,
                },
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 公共访问阻止配置已更新")
        except Exception as e:
            handle_error(e, "put public access block")

    # ── 跨区域复制 ────────────────────────────────────────────────

    def replication_get(self, bucket: str) -> None:
        """查看 bucket 跨区域复制配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket replication-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_replication(Bucket=bucket)
            print_json(response.get("ReplicationConfiguration", {}))
        except ClientError as e:
            if e.response["Error"]["Code"] == "ReplicationConfigurationNotFoundError":
                console.print("[yellow]未配置跨区域复制[/yellow]")
            else:
                handle_error(e, "get replication")

    def replication_put(self, bucket: str, config_file: str) -> None:
        """设置 bucket 跨区域复制配置

        Args:
            bucket:      Bucket 名称
            config_file: 复制配置 JSON 文件路径

        示例:
            s3c bucket replication-put my-bucket replication.json
        """
        try:
            with open(config_file, "r", encoding="utf-8") as f:
                config = json.load(f)
            s3 = get_s3_client()
            s3.put_bucket_replication(Bucket=bucket, ReplicationConfiguration=config)
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 跨区域复制配置已更新")
        except Exception as e:
            handle_error(e, "put replication")

    def replication_delete(self, bucket: str) -> None:
        """删除 bucket 跨区域复制配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket replication-delete my-bucket
        """
        try:
            s3 = get_s3_client()
            s3.delete_bucket_replication(Bucket=bucket)
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 跨区域复制配置已删除")
        except Exception as e:
            handle_error(e, "delete replication")

    # ── 通知 ─────────────────────────────────────────────────────

    def notification_get(self, bucket: str) -> None:
        """查看 bucket 事件通知配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket notification-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_notification_configuration(Bucket=bucket)
            response.pop("ResponseMetadata", None)
            print_json(response)
        except Exception as e:
            handle_error(e, "get notification")

    def notification_put(self, bucket: str, config_file: str) -> None:
        """设置 bucket 事件通知配置

        Args:
            bucket:      Bucket 名称
            config_file: 通知配置 JSON 文件路径

        示例:
            s3c bucket notification-put my-bucket notification.json
        """
        try:
            with open(config_file, "r", encoding="utf-8") as f:
                config = json.load(f)
            s3 = get_s3_client()
            s3.put_bucket_notification_configuration(
                Bucket=bucket,
                NotificationConfiguration=config,
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 通知配置已更新")
        except Exception as e:
            handle_error(e, "put notification")

    # ── 加速 ─────────────────────────────────────────────────────

    def accelerate_get(self, bucket: str) -> None:
        """查看 bucket 传输加速配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket accelerate-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_accelerate_configuration(Bucket=bucket)
            status = response.get("Status", "Suspended")
            console.print(f"传输加速: [bold]{status}[/bold]")
        except Exception as e:
            handle_error(e, "get accelerate")

    def accelerate_put(self, bucket: str, enable: bool = True) -> None:
        """设置 bucket 传输加速

        Args:
            bucket: Bucket 名称
            enable: True 启用，False 禁用（默认 True）

        示例:
            s3c bucket accelerate-put my-bucket
            s3c bucket accelerate-put my-bucket --no-enable
        """
        try:
            status = "Enabled" if enable else "Suspended"
            s3 = get_s3_client()
            s3.put_bucket_accelerate_configuration(
                Bucket=bucket,
                AccelerateConfiguration={"Status": status},
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 传输加速已{('启用' if enable else '禁用')}")
        except Exception as e:
            handle_error(e, "put accelerate")

    # ── 请求支付 ──────────────────────────────────────────────────

    def request_payment_get(self, bucket: str) -> None:
        """查看 bucket 请求支付配置

        Args:
            bucket: Bucket 名称

        示例:
            s3c bucket request-payment-get my-bucket
        """
        try:
            s3 = get_s3_client()
            response = s3.get_bucket_request_payment(Bucket=bucket)
            payer = response.get("Payer", "BucketOwner")
            console.print(f"请求支付方: [bold]{payer}[/bold]")
        except Exception as e:
            handle_error(e, "get request payment")

    def request_payment_put(self, bucket: str, requester: bool = False) -> None:
        """设置 bucket 请求支付方

        Args:
            bucket:    Bucket 名称
            requester: True = 请求者付费，False = Bucket 所有者付费（默认 False）

        示例:
            s3c bucket request-payment-put my-bucket --requester
        """
        try:
            payer = "Requester" if requester else "BucketOwner"
            s3 = get_s3_client()
            s3.put_bucket_request_payment(
                Bucket=bucket,
                RequestPaymentConfiguration={"Payer": payer},
            )
            console.print(f"[green]✓[/green] [cyan]{bucket}[/cyan] 请求支付方已设为 {payer}")
        except Exception as e:
            handle_error(e, "put request payment")
