#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright: Contributors to the Ansible project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import annotations

DOCUMENTATION = r"""
---
module: s3_object
version_added: 1.0.0
short_description: Manage objects in S3
description:
  - This module allows the user to manage the objects and directories within S3 buckets. Includes
    support for creating and deleting objects and directories, retrieving objects as files or
    strings, generating download links and copying objects that are already stored in Amazon S3.
  - S3 buckets can be created or deleted using the M(amazon.aws.s3_bucket) module.
  - Compatible with AWS, DigitalOcean, Ceph, Walrus, FakeS3 and StorageGRID.
  - When using non-AWS services, O(endpoint_url) should be specified.
options:
  bucket:
    description:
      - Bucket name.
    required: true
    type: str
  dest:
    description:
      - The destination file path when downloading an object/key when O(mode=get).
      - Ignored when O(mode) is not V(get).
    type: path
  encrypt:
    description:
      - Asks for server-side encryption of the objects when O(mode=put) or O(mode=copy).
      - Ignored when O(mode) is neither V(put) nor V(copy).
    default: true
    type: bool
  encryption_mode:
    description:
      - The encryption mode to use if O(encrypt=true).
    default: AES256
    choices:
      - AES256
      - aws:kms
    type: str
  expiry:
    description:
      - Time limit (in seconds) for the URL generated and returned by S3/Walrus when performing a
        O(mode=put) or O(mode=geturl) operation.
      - Ignored when O(mode) is neither V(put) nor V(geturl).
    default: 600
    aliases: ['expiration']
    type: int
  headers:
    description:
      - Custom headers to use when O(mode=put) as a dictionary of key value pairs.
      - Keys that match supported S3 object arguments are promoted to top‑level ExtraArgs. Supported keys include
        C(ContentType), C(Content-Disposition), C(ContentEncoding), C(ContentLanguage), C(CacheControl), C(Expires),
        C(ACL), C(GrantFullControl), C(GrantRead), C(GrantReadACP), C(GrantWriteACP), C(StorageClass),
        C(ServerSideEncryption), C(SSECustomerAlgorithm), C(SSECustomerKey), C(SSECustomerKeyMD5), C(SSEKMSKeyId),
        and C(WebsiteRedirectLocation). Remaining keys are stored under C(Metadata).
      - Both header name styles C(ContentType) and C(Content-Type) are supported. Underscore variants like
        C(content_type) are not promoted and will be placed under C(Metadata).
      - If C(ContentType) is not provided, a type is guessed from C(src) when uploading from a file. When uploading
        using C(content) or C(content_base64) the default is C(binary/octet-stream).
      - Ignored when O(mode) is not V(put).
    type: dict
  marker:
    description:
      - Specifies the key to start with when using list mode. Object keys are returned in
        alphabetical order, starting with key after the marker in order.
    type: str
  max_keys:
    description:
      - Max number of results to return when O(mode=list)
      - When not set, B(all) keys will be returned.
      - Ignored when O(mode) is not V(list).
    type: int
  metadata:
    description:
      - Metadata to use when O(mode=copy), O(mode=create) or O(mode=put) as a dictionary of key value pairs.
      - Keys that match supported S3 object arguments are promoted to top‑level ExtraArgs (for example C(ContentType)).
        Remaining keys are applied as user metadata under C(Metadata).
    type: dict
  mode:
    description:
      - Switches the module behaviour between
      - 'V(put): upload'
      - 'V(get): download'
      - 'V(geturl): return download URL'
      - 'V(getstr): download object as string'
      - 'V(list): list keys'
      - 'V(create): create bucket directories'
      - 'V(delobj): delete object'
      - 'V(copy): copy object that is already stored in another bucket'
      - Support for creating and deleting buckets was removed in release 6.0.0.
        To create and manage the bucket itself please use the M(amazon.aws.s3_bucket) module.
      - Support for V(list) has been deprecated and will be removed in a release after 2026-11-01.
        The M(amazon.aws.s3_object_info) module should be used instead of V(list).
    required: true
    choices: ['get', 'put', 'create', 'geturl', 'getstr', 'delobj', 'list', 'copy']
    type: str
  object:
    description:
      - Key name of the object inside the bucket.
      - Can be used to create "virtual directories", see examples.
      - Object key names should not include the leading C(/), see
        U(https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html) for more
        information.
    type: str
  sig_v4:
    description:
      - Forces the Boto SDK to use Signature Version 4.
      - Only applies to get modes, O(mode=get), O(mode=getstr), O(mode=geturl).
    default: true
    type: bool
    version_added: 5.0.0
  permission:
    description:
      - This option lets the user set the canned permissions on the object/bucket that are created.
        The permissions that can be set are V(private), V(public-read), V(public-read-write),
        V(authenticated-read) for a bucket or V(private), V(public-read), V(public-read-write),
        V(aws-exec-read), V(authenticated-read), V(bucket-owner-read), V(bucket-owner-full-control)
        for an object. Multiple permissions can be specified as a list; although only the first one
        will be used during the initial upload of the file.
      - For a full list of permissions see the AWS documentation
        U(https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html#canned-acl).
    default: ['private']
    choices:
      - "private"
      - "public-read"
      - "public-read-write"
      - "aws-exec-read"
      - "authenticated-read"
      - "bucket-owner-read"
      - "bucket-owner-full-control"
    type: list
    elements: str
  prefix:
    description:
      - Limits the response to keys that begin with the specified prefix for list mode.
    default: ""
    type: str
  version:
    description:
      - Version ID of the object inside the bucket. Can be used to get a specific version of a file
        if versioning is enabled in the target bucket.
    type: str
  overwrite:
    description:
      - Force overwrite either locally on the filesystem or remotely with the object/key.
      - Used when O(mode=put) or O(mode=get).
      - Ignored when when O(mode) is neither V(put) nor V(get).
      - Must be a Boolean, V(always), V(never), V(different) or V(latest).
      - V(true) is the same as V(always).
      - V(false) is equal to V(never).
      - When this is set to C(different) the MD5 sum of the local file is compared with the 'ETag'
        of the object/key in S3.  The ETag may or may not be an MD5 digest of the object data. See
        the ETag response header here
        U(https://docs.aws.amazon.com/AmazonS3/latest/API/RESTCommonResponseHeaders.html).
      - When O(mode=get) and O(overwrite=latest) the last modified timestamp of local file
        is compared with the 'LastModified' of the object/key in S3.
    default: 'different'
    aliases: ['force']
    type: str
  retries:
    description:
     - On recoverable failure, how many times to retry before actually failing.
    default: 0
    type: int
    aliases: ['retry']
  dualstack:
    description:
      - Enables Amazon S3 Dual-Stack Endpoints, allowing S3 communications using both IPv4 and IPv6.
      - Support for passing O(dualstack) and O(endpoint_url) at the same time has been deprecated,
        the dualstack endpoints are automatically configured using the configured O(region).
        Support will be removed in a release after 2024-12-01.
    type: bool
    default: false
  ceph:
    description:
      - Enable API compatibility with Ceph RGW.
      - It takes into account the S3 API subset working with Ceph in order to provide the same module
        behaviour where possible.
      - Requires O(endpoint_url) if O(ceph=true).
    aliases: ['rgw']
    default: false
    type: bool
  src:
    description:
      - The source file path when performing a C(put) operation.
      - One of O(content), O(content_base64) or O(src) must be specified when O(mode=put)
        otherwise ignored.
    type: path
  content:
    description:
      - The content to C(put) into an object.
      - The parameter value will be treated as a string and converted to UTF-8 before sending it to
        S3.
      - To send binary data, use the O(content_base64) parameter instead.
      - One of O(content), O(content_base64) or O(src) must be specified when O(mode=put)
        otherwise ignored.
    version_added: "1.3.0"
    type: str
  content_base64:
    description:
      - The base64-encoded binary data to C(put) into an object.
      - Use this if you need to put raw binary data, and don't forget to encode in base64.
      - One of O(content), O(content_base64) or O(src) must be specified when O(mode=put)
        otherwise ignored.
    version_added: "1.3.0"
    type: str
  ignore_nonexistent_bucket:
    description:
      - Overrides initial bucket lookups in case bucket or IAM policies are restrictive.
      - This can be useful when a user may have the C(GetObject) permission but no other
        permissions. In which case using O(mode=get) will fail unless
        O(ignore_nonexistent_bucket=true) is specified.
    type: bool
    default: false
  encryption_kms_key_id:
    description:
      - KMS key id to use when encrypting objects using O(encryption_mode=aws:kms).
      - Ignored if O(encryption_mode) is not V(aws:kms).
    type: str
  copy_src:
    description:
    - The source details of the object to copy.
    - Required if O(mode=copy).
    type: dict
    version_added: 2.0.0
    suboptions:
      bucket:
        type: str
        description:
        - The name of the source bucket.
        required: true
      object:
        type: str
        description:
        - key name of the source object.
        - if not specified, all the objects of the O(copy_src.bucket) will be copied into the specified bucket.
        required: false
      version_id:
        type: str
        description:
        - version ID of the source object.
      prefix:
        description:
        - Copy all the keys that begin with the specified prefix.
        - Ignored if O(copy_src.object) is supplied.
        default: ""
        type: str
        version_added: 6.2.0
  validate_bucket_name:
    description:
      - Whether the bucket name should be validated to conform to AWS S3 naming rules.
      - On by default, this may be disabled for S3 backends that do not enforce these rules.
      - See the Amazon documentation for more information about bucket naming rules
        U(https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html).
    type: bool
    version_added: 3.1.0
    default: True
  expected_bucket_owner:
    description:
      - The account ID of the expected bucket owner.
      - If the account ID that you provide does not match the actual owner of the bucket,
        the request fails with the HTTP status code 403 Forbidden (access denied).
    type: str
    version_added: 8.2.0
author:
  - "Lester Wade (@lwade)"
  - "Sloane Hertel (@s-hertel)"
  - "Alina Buzachis (@alinabuzachis)"
notes:
  - Support for O(tags) and O(purge_tags) was added in release 2.0.0.
  - For Walrus O(endpoint_url) should be set to the FQDN of the endpoint with neither scheme nor path.
  - Support for creating and deleting buckets was removed in release 6.0.0.
extends_documentation_fragment:
  - amazon.aws.common.modules
  - amazon.aws.region.modules
  - amazon.aws.tags
  - amazon.aws.boto3
"""

EXAMPLES = r"""
- name: Simple PUT operation
  amazon.aws.s3_object:
    bucket: mybucket
    object: /my/desired/key.txt
    src: /usr/local/myfile.txt
    mode: put

- name: PUT operation from a rendered template
  amazon.aws.s3_object:
    bucket: mybucket
    object: /object.yaml
    content: "{{ lookup('template', 'templates/object.yaml.j2') }}"
    mode: put

- name: PUT content with explicit ContentType and ContentDisposition
  amazon.aws.s3_object:
    bucket: mybucket
    object: /index.html
    content: "<html>Hello</html>\n"
    mode: put
    headers:
      ContentType: "text/html; charset=utf-8"
      ContentDisposition: inline

- name: Simple PUT operation in Ceph RGW S3
  amazon.aws.s3_object:
    bucket: mybucket
    object: /my/desired/key.txt
    src: /usr/local/myfile.txt
    mode: put
    ceph: true
    endpoint_url: "http://localhost:8000"

- name: Simple GET operation
  amazon.aws.s3_object:
    bucket: mybucket
    object: /my/desired/key.txt
    dest: /usr/local/myfile.txt
    mode: get

- name: Get a specific version of an object.
  amazon.aws.s3_object:
    bucket: mybucket
    object: /my/desired/key.txt
    version: 48c9ee5131af7a716edc22df9772aa6f
    dest: /usr/local/myfile.txt
    mode: get

- name: PUT/upload with metadata
  amazon.aws.s3_object:
    bucket: mybucket
    object: /my/desired/key.txt
    src: /usr/local/myfile.txt
    mode: put
    metadata:
      Content-Encoding: gzip
      Cache-Control: no-cache

- name: PUT/upload with custom headers
  amazon.aws.s3_object:
    bucket: mybucket
    object: /my/desired/key.txt
    src: /usr/local/myfile.txt
    mode: put
    headers:
      GrantFullControl: "emailAddress=owner@example.com"

- name: List keys simple
  amazon.aws.s3_object:
    bucket: mybucket
    mode: list

- name: List keys all options
  amazon.aws.s3_object:
    bucket: mybucket
    mode: list
    prefix: /my/desired/
    marker: /my/desired/0023.txt
    max_keys: 472

- name: GET an object but don't download if the file checksums match. New in 2.0
  amazon.aws.s3_object:
    bucket: mybucket
    object: /my/desired/key.txt
    dest: /usr/local/myfile.txt
    mode: get
    overwrite: different

- name: Delete an object from a bucket
  amazon.aws.s3_object:
    bucket: mybucket
    object: /my/desired/key.txt
    mode: delobj

- name: Copy an object already stored in another bucket
  amazon.aws.s3_object:
    bucket: mybucket
    object: /my/desired/key.txt
    mode: copy
    copy_src:
      bucket: srcbucket
      object: /source/key.txt

- name: Copy all the objects with name starting with 'ansible_'
  amazon.aws.s3_object:
    bucket: mybucket
    mode: copy
    copy_src:
      bucket: srcbucket
      prefix: 'ansible_'
"""

RETURN = r"""
msg:
  description: Message indicating the status of the operation.
  returned: always
  type: str
  sample: "PUT operation complete"
url:
  description: URL of the object.
  returned: (for put and geturl operations)
  type: str
  sample: "https://my-bucket.s3.amazonaws.com/my-key.txt?AWSAccessKeyId=<access-key>&Expires=1506888865&Signature=<signature>"
expiry:
  description: Number of seconds the presigned url is valid for.
  returned: (for geturl operation)
  type: int
  sample: 600
contents:
  description: Contents of the object as string.
  returned: (for getstr operation)
  type: str
  sample: "Hello, world!"
s3_keys:
  description: List of object keys.
  returned: (for list operation)
  type: list
  elements: str
  sample:
  - prefix1/
  - prefix1/key1
  - prefix1/key2
tags:
    description: Tags of the s3 object.
    returned: always
    type: dict
    sample: {
                "Owner": "dev001",
                "env": "test"
            }
"""

import base64
import copy
import mimetypes
import os
import typing

if typing.TYPE_CHECKING:
    from typing import Any
    from typing import Dict
    from typing import List
    from typing import Optional
    from typing import Tuple

    from ansible_collections.amazon.aws.plugins.module_utils.botocore import ClientType

from ansible.module_utils.basic import to_native

from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
from ansible_collections.amazon.aws.plugins.module_utils.retries import AWSRetry
from ansible_collections.amazon.aws.plugins.module_utils.s3 import HAS_MD5
from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3ACLSupportError
from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3Error
from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3PermissionsError
from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3Sigv4RequiredError
from ansible_collections.amazon.aws.plugins.module_utils.s3 import AnsibleS3SupportError
from ansible_collections.amazon.aws.plugins.module_utils.s3 import calculate_etag
from ansible_collections.amazon.aws.plugins.module_utils.s3 import calculate_etag_content
from ansible_collections.amazon.aws.plugins.module_utils.s3 import copy_s3_object
from ansible_collections.amazon.aws.plugins.module_utils.s3 import delete_s3_object
from ansible_collections.amazon.aws.plugins.module_utils.s3 import download_s3_file
from ansible_collections.amazon.aws.plugins.module_utils.s3 import ensure_s3_object_tags
from ansible_collections.amazon.aws.plugins.module_utils.s3 import generate_s3_presigned_url
from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_bucket_ownership_controls
from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_object_content
from ansible_collections.amazon.aws.plugins.module_utils.s3 import get_s3_object_tagging
from ansible_collections.amazon.aws.plugins.module_utils.s3 import head_s3_object
from ansible_collections.amazon.aws.plugins.module_utils.s3 import list_bucket_object_keys
from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_object
from ansible_collections.amazon.aws.plugins.module_utils.s3 import put_s3_object_acl
from ansible_collections.amazon.aws.plugins.module_utils.s3 import s3_bucket_exists
from ansible_collections.amazon.aws.plugins.module_utils.s3 import s3_extra_params
from ansible_collections.amazon.aws.plugins.module_utils.s3 import s3_object_exists
from ansible_collections.amazon.aws.plugins.module_utils.s3 import upload_s3_file
from ansible_collections.amazon.aws.plugins.module_utils.s3 import validate_bucket_name


def key_check(
    module: AnsibleAWSModule,
    s3: ClientType,
    bucket: str,
    obj: str,
    version: Optional[str] = None,
    validate: bool = True,
) -> bool:
    """Check if object exists with optional validation."""
    try:
        exists = s3_object_exists(s3, bucket, obj, version_id=version)
        return exists
    except AnsibleS3PermissionsError:
        if validate:
            raise  # Let the original AnsibleS3PermissionsError propagate
        return False  # If not validating, treat permission errors as "doesn't exist"
    # Let other AnsibleS3Error exceptions propagate naturally


def etag_compare(
    module: AnsibleAWSModule,
    s3: ClientType,
    bucket: str,
    obj: str,
    version: Optional[str] = None,
    local_file: Optional[str] = None,
    content: Optional[bytes] = None,
) -> bool:
    s3_etag = head_s3_object(s3, bucket, obj, version_id=version).get("ETag")
    if local_file is not None:
        local_etag = calculate_etag(module, local_file, s3_etag, s3, bucket, obj, version)
    else:
        local_etag = calculate_etag_content(module, content, s3_etag, s3, bucket, obj, version)
    return s3_etag == local_etag


def get_s3_last_modified_timestamp(
    s3: ClientType,
    bucket: str,
    obj: str,
    version: Optional[str] = None,
) -> Optional[float]:
    last_modified = None
    obj_info = head_s3_object(s3, bucket, obj, version_id=version)
    if obj_info:
        last_modified = obj_info["LastModified"].timestamp()
    return last_modified


def is_local_object_latest(
    s3: ClientType,
    bucket: str,
    obj: str,
    version: Optional[str] = None,
    local_file: Optional[str] = None,
) -> bool:
    s3_last_modified = get_s3_last_modified_timestamp(s3, bucket, obj, version)
    if not os.path.exists(local_file):
        return False
    local_last_modified = os.path.getmtime(local_file)
    return s3_last_modified <= local_last_modified


def bucket_check(module: AnsibleAWSModule, s3: ClientType, bucket: str, validate: bool = True) -> None:
    """Check if bucket exists and is accessible."""
    try:
        exists = s3_bucket_exists(s3, bucket)
        if not exists and validate:
            raise AnsibleS3Error(
                message=f"Bucket '{bucket}' not found. "
                "Support for automatically creating buckets was removed in release 6.0.0. "
                "The amazon.aws.s3_bucket module can be used to create buckets."
            )
    except AnsibleS3PermissionsError:
        if validate:
            raise  # Let the original AnsibleS3PermissionsError propagate
        # If not validating, silently ignore permission errors
    # Let other AnsibleS3Error exceptions propagate naturally


def put_object_acl(
    module: AnsibleAWSModule,
    s3: ClientType,
    bucket: str,
    obj: str,
    params: Optional[Dict] = None,
) -> None:
    if params:
        put_s3_object(s3, **params)

    for acl in module.params.get("permission"):
        try:
            put_s3_object_acl(s3, bucket, obj, acl)
        except AnsibleS3ACLSupportError:
            module.warn("PutObjectAcl operation : The bucket does not allow ACLs.")
            return
        except AnsibleS3SupportError:
            # S3 drop-ins (MinIO, Ceph, etc.) may not support ACL operations
            module.warn(
                "Setting object ACLs is not supported by your storage provider. "
                "Set the 'permission' parameter to an empty list to avoid this warning."
            )
            return  # Don't try other ACLs if this one failed


def create_dirkey(
    module: AnsibleAWSModule,
    s3: ClientType,
    bucket: str,
    obj: str,
    encrypt: bool,
    expiry: int,
    metadata: Optional[Dict],
) -> None:
    if module.check_mode:
        module.exit_json(msg="PUT operation skipped - running in check mode", changed=True)
    params = {"Bucket": bucket, "Key": obj, "Body": b""}
    params.update(
        get_extra_params(
            encrypt,
            module.params.get("encryption_mode"),
            module.params.get("encryption_kms_key_id"),
            metadata,
        )
    )
    put_object_acl(module, s3, bucket, obj, params)

    # Tags
    tags, _changed = ensure_s3_object_tags(s3, bucket, obj, module.params.get("tags"), module.params.get("purge_tags"))

    url = generate_s3_presigned_url(s3, bucket, obj, client_method="put_object", expiry=expiry)

    module.exit_json(
        msg=f"Virtual directory {obj} created in bucket {bucket}",
        url=url,
        tags=tags,
        changed=True,
    )


def guess_content_type(src: Optional[str]) -> str:
    if src:
        content_type = mimetypes.guess_type(src)[0]
        if content_type:
            return content_type

    # S3 default content type
    return "binary/octet-stream"


def get_extra_params(
    encrypt: Optional[bool] = None,
    encryption_mode: Optional[str] = None,
    encryption_kms_key_id: Optional[str] = None,
    metadata: Optional[Dict] = None,
) -> Dict:
    extra = {}
    if encrypt:
        extra["ServerSideEncryption"] = encryption_mode
    if encryption_kms_key_id and encryption_mode == "aws:kms":
        extra["SSEKMSKeyId"] = encryption_kms_key_id
    if metadata:
        extra["Metadata"] = {}
        # determine object metadata and extra arguments
        for option in metadata:
            extra_args_option = option_in_extra_args(option)
            if extra_args_option:
                extra[extra_args_option] = metadata[option]
            else:
                extra["Metadata"][option] = metadata[option]
    return extra


def option_in_extra_args(option: str) -> Optional[str]:
    temp_option = option.replace("-", "").lower()

    allowed_extra_args = {
        "acl": "ACL",
        "cachecontrol": "CacheControl",
        "contentdisposition": "ContentDisposition",
        "contentencoding": "ContentEncoding",
        "contentlanguage": "ContentLanguage",
        "contenttype": "ContentType",
        "expires": "Expires",
        "grantfullcontrol": "GrantFullControl",
        "grantread": "GrantRead",
        "grantreadacp": "GrantReadACP",
        "grantwriteacp": "GrantWriteACP",
        "metadata": "Metadata",
        "requestpayer": "RequestPayer",
        "serversideencryption": "ServerSideEncryption",
        "storageclass": "StorageClass",
        "ssecustomeralgorithm": "SSECustomerAlgorithm",
        "ssecustomerkey": "SSECustomerKey",
        "ssecustomerkeymd5": "SSECustomerKeyMD5",
        "ssekmskeyid": "SSEKMSKeyId",
        "websiteredirectlocation": "WebsiteRedirectLocation",
    }

    if temp_option in allowed_extra_args:
        return allowed_extra_args[temp_option]
    return None


def upload_s3file(
    module: AnsibleAWSModule,
    s3: ClientType,
    bucket: str,
    obj: str,
    expiry: int,
    metadata: Optional[Dict],
    encrypt: bool,
    headers: Optional[Dict],
    src: Optional[str] = None,
    content: Optional[bytes] = None,
    acl_disabled: bool = False,
) -> None:
    if module.check_mode:
        module.exit_json(msg="PUT operation skipped - running in check mode", changed=True)
    extra = get_extra_params(
        encrypt,
        module.params.get("encryption_mode"),
        module.params.get("encryption_kms_key_id"),
        metadata,
    )
    # Promote supported headers to boto3 ExtraArgs and place unknown ones under Metadata
    if headers:
        if not isinstance(headers, dict):
            module.warn("'headers' must be a dict; ignoring non-dict value")
        else:
            for option, value in headers.items():
                extra_arg_key = option_in_extra_args(option)
                if extra_arg_key:
                    extra[extra_arg_key] = value
                else:
                    # Fall back to Metadata for non-ExtraArgs headers
                    extra.setdefault("Metadata", {})
                    extra["Metadata"][option] = value
    if module.params.get("permission"):
        permissions = module.params["permission"]
        if isinstance(permissions, str):
            extra["ACL"] = permissions
        elif isinstance(permissions, list):
            extra["ACL"] = permissions[0]

    if "ContentType" not in extra:
        extra["ContentType"] = guess_content_type(src)

    if src:
        upload_s3_file(s3, src, bucket, obj, extra)
    else:
        # For in-memory content uploads, use put_object so promoted headers
        # (e.g. ContentType, ContentDisposition, CacheControl) are applied consistently
        params = {"Bucket": bucket, "Key": obj, "Body": content}
        params.update(extra)
        put_s3_object(s3, **params)

    if not acl_disabled:
        put_object_acl(module, s3, bucket, obj)

    # Tags
    tags, _changed = ensure_s3_object_tags(s3, bucket, obj, module.params.get("tags"), module.params.get("purge_tags"))

    url = generate_s3_presigned_url(s3, bucket, obj, client_method="put_object", expiry=expiry)

    module.exit_json(msg="PUT operation complete", url=url, tags=tags, changed=True)


def download_s3file(
    module: AnsibleAWSModule,
    s3: ClientType,
    bucket: str,
    obj: str,
    dest: str,
    retries: int,
    version: Optional[str] = None,
) -> None:
    if module.check_mode:
        module.exit_json(msg="GET operation skipped - running in check mode", changed=True)

    extra_args = {"VersionId": version} if version else {}
    download_s3_file(s3, bucket, obj, dest, extra_args)
    module.exit_json(msg="GET operation complete", changed=True)


def download_s3str(
    module: AnsibleAWSModule,
    s3: ClientType,
    bucket: str,
    obj: str,
    version: Optional[str] = None,
) -> None:
    if module.check_mode:
        module.exit_json(msg="GET operation skipped - running in check mode", changed=True)
    contents = to_native(get_s3_object_content(s3, bucket, obj, version_id=version))
    module.exit_json(msg="GET operation complete", contents=contents, changed=True)


def get_download_url(
    module: AnsibleAWSModule,
    s3: ClientType,
    bucket: str,
    obj: str,
    expiry: int,
    tags: Optional[Dict] = None,
    changed: bool = True,
) -> None:
    url = generate_s3_presigned_url(s3, bucket, obj, client_method="get_object", expiry=expiry)
    module.exit_json(
        msg="Download url:",
        url=url,
        tags=tags,
        expiry=expiry,
        changed=changed,
    )


def get_current_object_tags_dict(
    module: AnsibleAWSModule,
    s3: ClientType,
    bucket: str,
    obj: str,
    version: Optional[str] = None,
) -> Dict:
    """Get object tags with module-specific parameter handling."""
    kwargs = {}
    if module.params.get("expected_bucket_owner"):
        kwargs["ExpectedBucketOwner"] = module.params["expected_bucket_owner"]

    try:
        return get_s3_object_tagging(s3, bucket, obj, version_id=version, **kwargs)
    except AnsibleS3SupportError:
        module.warn("GetObjectTagging is not implemented by your storage provider.")
        return {}
    # Let other AnsibleS3Error exceptions propagate naturally


def get_binary_content(s3_vars: Dict) -> Optional[bytes]:
    # the content will be uploaded as a byte string, so we must encode it first
    bincontent = None
    if s3_vars.get("content") is not None:
        bincontent = s3_vars["content"].encode("utf-8")
    if s3_vars.get("content_base64") is not None:
        bincontent = base64.standard_b64decode(s3_vars["content_base64"])
    return bincontent


def do_s3_object_get(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None:
    keyrtn = key_check(
        module,
        connection,
        s3_vars["bucket"],
        s3_vars["object"],
        version=s3_vars["version"],
        validate=s3_vars["validate"],
    )
    if not keyrtn:
        if s3_vars["version"]:
            module.fail_json(msg=f"Key {s3_vars['object']} with version id {s3_vars['version']} does not exist.")
        module.fail_json(msg=f"Key {s3_vars['object']} does not exist.")
    if s3_vars["dest"] and os.path.exists(s3_vars["dest"]) and s3_vars["overwrite"] != "always":
        if s3_vars["overwrite"] == "never":
            module.exit_json(
                msg="Local object already exists and overwrite is disabled.",
                changed=False,
            )
        if s3_vars["overwrite"] == "different" and etag_compare(
            module,
            connection,
            s3_vars["bucket"],
            s3_vars["object"],
            version=s3_vars["version"],
            local_file=s3_vars["dest"],
        ):
            module.exit_json(
                msg="Local and remote object are identical, ignoring. Use overwrite=always parameter to force.",
                changed=False,
            )
        if s3_vars["overwrite"] == "latest" and is_local_object_latest(
            connection,
            s3_vars["bucket"],
            s3_vars["object"],
            version=s3_vars["version"],
            local_file=s3_vars["dest"],
        ):
            module.exit_json(
                msg="Local object is latest, ignoreing. Use overwrite=always parameter to force.",
                changed=False,
            )

    download_s3file(
        module,
        connection,
        s3_vars["bucket"],
        s3_vars["object"],
        s3_vars["dest"],
        s3_vars["retries"],
        version=s3_vars["version"],
    )

    module.exit_json(failed=False)


def do_s3_object_put(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None:
    # if putting an object in a bucket yet to be created, acls for the bucket and/or the object may be specified
    # these were separated into the variables bucket_acl and object_acl above

    if s3_vars["src"] is not None and not os.path.exists(s3_vars["src"]):
        module.fail_json(msg=f'Local object "{s3_vars["src"]}" does not exist for PUT operation')

    keyrtn = key_check(
        module,
        connection,
        s3_vars["bucket"],
        s3_vars["object"],
        version=s3_vars["version"],
        validate=s3_vars["validate"],
    )

    # the content will be uploaded as a byte string, so we must encode it first
    bincontent = get_binary_content(s3_vars)

    if keyrtn and s3_vars["overwrite"] != "always":
        if s3_vars["overwrite"] == "never" or etag_compare(
            module,
            connection,
            s3_vars["bucket"],
            s3_vars["object"],
            version=s3_vars["version"],
            local_file=s3_vars["src"],
            content=bincontent,
        ):
            # Return the download URL for the existing object and ensure tags are updated
            tags, tags_update = ensure_s3_object_tags(
                connection,
                s3_vars["bucket"],
                s3_vars["object"],
                module.params.get("tags"),
                module.params.get("purge_tags"),
            )
            get_download_url(
                module,
                connection,
                s3_vars["bucket"],
                s3_vars["object"],
                s3_vars["expiry"],
                tags,
                changed=tags_update,
            )

    # only use valid object acls for the upload_s3file function
    if not s3_vars["acl_disabled"]:
        s3_vars["permission"] = s3_vars["object_acl"]
    upload_s3file(
        module,
        connection,
        s3_vars["bucket"],
        s3_vars["object"],
        s3_vars["expiry"],
        s3_vars["metadata"],
        s3_vars["encrypt"],
        s3_vars["headers"],
        src=s3_vars["src"],
        content=bincontent,
        acl_disabled=s3_vars["acl_disabled"],
    )
    module.exit_json(failed=False)


def do_s3_object_delobj(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None:
    if module.check_mode:
        module.exit_json(
            msg="DELETE operation skipped - running in check mode",
            changed=True,
        )
    delete_s3_object(
        connection,
        s3_vars["bucket"],
        s3_vars["object"],
    )
    module.exit_json(msg=f"Object {s3_vars['object']} deleted from bucket {s3_vars['bucket']}.", changed=True)


def do_s3_object_list(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None:
    # If the bucket does not exist then bail out
    keys = list_bucket_object_keys(
        connection,
        s3_vars["bucket"],
        prefix=s3_vars["prefix"],
        start_after=s3_vars["marker"],
        max_keys=s3_vars["max_keys"],
    )
    module.exit_json(msg="LIST operation complete", s3_keys=keys)


def do_s3_object_create(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None:
    # if both creating a bucket and putting an object in it, acls for the bucket and/or the object may be specified
    # these were separated above into the variables bucket_acl and object_acl

    if not s3_vars["object"].endswith("/"):
        s3_vars["object"] = s3_vars["object"] + "/"

    if key_check(module, connection, s3_vars["bucket"], s3_vars["object"]):
        module.exit_json(
            msg=f"Bucket {s3_vars['bucket']} and key {s3_vars['object']} already exists.",
            changed=False,
        )
    if not s3_vars["acl_disabled"]:
        # setting valid object acls for the create_dirkey function
        s3_vars["permission"] = s3_vars["object_acl"]
    create_dirkey(
        module,
        connection,
        s3_vars["bucket"],
        s3_vars["object"],
        s3_vars["encrypt"],
        s3_vars["expiry"],
        s3_vars["metadata"],
    )


def do_s3_object_geturl(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None:
    if key_check(
        module,
        connection,
        s3_vars["bucket"],
        s3_vars["object"],
        version=s3_vars["version"],
        validate=s3_vars["validate"],
    ):
        tags = get_current_object_tags_dict(
            module,
            connection,
            s3_vars["bucket"],
            s3_vars["object"],
            version=s3_vars["version"],
        )
        get_download_url(
            module,
            connection,
            s3_vars["bucket"],
            s3_vars["object"],
            s3_vars["expiry"],
            tags,
        )
    module.fail_json(msg=f"Key {s3_vars['object']} does not exist.")


def do_s3_object_getstr(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None:
    if s3_vars["bucket"] and s3_vars["object"]:
        if key_check(
            module,
            connection,
            s3_vars["bucket"],
            s3_vars["object"],
            version=s3_vars["version"],
            validate=s3_vars["validate"],
        ):
            download_s3str(
                module,
                connection,
                s3_vars["bucket"],
                s3_vars["object"],
                version=s3_vars["version"],
            )
        elif s3_vars["version"]:
            module.fail_json(msg=f"Key {s3_vars['object']} with version id {s3_vars['version']} does not exist.")
        else:
            module.fail_json(msg=f"Key {s3_vars['object']} does not exist.")


def check_object_tags(module: AnsibleAWSModule, connection: ClientType, bucket: str, obj: str) -> bool:
    tags = module.params.get("tags")
    purge_tags = module.params.get("purge_tags")
    diff = False
    if tags:
        current_tags_dict = get_current_object_tags_dict(module, connection, bucket, obj)
        if not purge_tags:
            # Ensure existing tags that aren't updated by desired tags remain
            current_tags_dict.update(tags)
        diff = current_tags_dict != tags
    return diff


def calculate_object_etag(
    module: AnsibleAWSModule, s3: ClientType, bucket: str, obj: str, head_etag: str, version: Optional[str] = None
) -> str:
    etag = head_etag
    if "-" in etag:
        # object has been created using multipart upload, compute ETag using
        # object content to ensure idempotency.
        contents = get_s3_object_content(s3, bucket, obj, version_id=version)
        # Set ETag to None, to force function to compute ETag from content
        etag = calculate_etag_content(module, contents, None, s3, bucket, obj)
    return etag


def copy_object_to_bucket(
    module: AnsibleAWSModule,
    s3: ClientType,
    bucket: str,
    obj: str,
    encrypt: bool,
    metadata: Optional[Dict],
    validate: bool,
    src_bucket: str,
    src_obj: str,
    versionId: Optional[str] = None,
) -> Tuple[bool, Dict]:
    if not key_check(module, s3, src_bucket, src_obj, version=versionId, validate=validate):
        # Key does not exist in source bucket
        module.exit_json(
            msg=f"Key {src_obj} does not exist in bucket {src_bucket}.",
            changed=False,
        )

    s_obj_info = head_s3_object(s3, src_bucket, src_obj, version_id=versionId)
    d_obj_info = head_s3_object(s3, bucket, obj, version_id=None)
    do_match = True
    diff_msg = None
    if d_obj_info:
        src_etag = calculate_object_etag(module, s3, src_bucket, src_obj, s_obj_info.get("ETag"), versionId)
        dst_etag = calculate_object_etag(module, s3, bucket, obj, d_obj_info.get("ETag"))
        if src_etag != dst_etag:
            # Source and destination objects ETag differ
            do_match = False
            diff_msg = "ETag from source and destination differ"
        if do_match and metadata and metadata != d_obj_info.get("Metadata"):
            # Metadata from module inputs differs from what has been retrieved from object header
            diff_msg = "Would have update object Metadata if not running in check mode."
            do_match = False
    else:
        # The destination object does not exists
        do_match = False
        diff_msg = "Would have copy object if not running in check mode."

    if do_match:
        # S3 objects are equals, ensure tags will not be updated
        if module.check_mode:
            changed = check_object_tags(module, s3, bucket, obj)
            result = {}
            if changed:
                result.update({"msg": "Would have update object tags if not running in check mode."})
            return changed, result

        # Ensure tags
        tags, changed = ensure_s3_object_tags(
            s3, bucket, obj, module.params.get("tags"), module.params.get("purge_tags")
        )
        result = {"msg": "ETag from source and destination are the same"}
        if changed:
            result = {"msg": "tags successfully updated.", "tags": tags}
        return changed, result
    # S3 objects differ
    if module.check_mode:
        return True, {"msg": diff_msg}
    else:
        changed = True
        bucketsrc = {
            "Bucket": src_bucket,
            "Key": src_obj,
        }
        if versionId:
            bucketsrc.update({"VersionId": versionId})

        extra_args = get_extra_params(
            encrypt,
            module.params.get("encryption_mode"),
            module.params.get("encryption_kms_key_id"),
            metadata,
        )

        if metadata:
            # 'MetadataDirective' Specifies whether the metadata is copied from the source object or replaced
            # with metadata that's provided in the request. The default value is 'COPY', therefore when user
            # specifies a metadata we should set it to 'REPLACE'
            extra_args.update({"MetadataDirective": "REPLACE"})

        # perform a "managed" copy rather simply using copy_object.  This will automatically use
        # multi-part uploads where necessary (https://github.com/boto/boto3/issues/1715)
        copy_s3_object(s3, bucketsrc, bucket, obj, extra_args)

        # We can't set the ACLs & tags during the copy, update them afterwards
        put_object_acl(module, s3, bucket, obj)
        tags, tags_updated = ensure_s3_object_tags(
            s3, bucket, obj, module.params.get("tags"), module.params.get("purge_tags")
        )

        msg = f"Object copied from bucket {src_bucket} to bucket {bucket}."
        return changed, {"msg": msg, "tags": tags}


def do_s3_object_copy(module: AnsibleAWSModule, connection: ClientType, s3_vars: Dict) -> None:
    copy_src = module.params.get("copy_src")
    if not copy_src.get("object") and s3_vars["object"]:
        module.fail_json(
            msg="A destination object was specified while trying to copy all the objects from the source bucket."
        )
    src_bucket = copy_src.get("bucket")
    if not copy_src.get("object"):
        # copy recursively object(s) from source bucket to destination bucket
        # list all the objects from the source bucket
        keys = list_bucket_object_keys(connection, src_bucket, prefix=copy_src.get("prefix"))
        if len(keys) == 0:
            module.exit_json(msg=f"No object found to be copied from source bucket {src_bucket}.")

        changed = False
        number_keys_updated = 0
        for key in keys:
            updated, result = copy_object_to_bucket(
                module,
                connection,
                s3_vars["bucket"],
                key,
                s3_vars["encrypt"],
                s3_vars["metadata"],
                s3_vars["validate"],
                src_bucket,
                key,
                versionId=copy_src.get("version_id"),
            )
            changed |= updated
            number_keys_updated += 1 if updated else 0

        msg = f"object(s) from buckets '{src_bucket}' and '{s3_vars['bucket']}' are the same."
        if number_keys_updated:
            msg = f"{number_keys_updated} copied into bucket '{s3_vars['bucket']}'"
        module.exit_json(changed=changed, msg=msg)
    else:
        # copy single object from source bucket into destination bucket
        changed, result = copy_object_to_bucket(
            module,
            connection,
            s3_vars["bucket"],
            s3_vars["object"],
            s3_vars["encrypt"],
            s3_vars["metadata"],
            s3_vars["validate"],
            src_bucket,
            copy_src.get("object"),
            versionId=copy_src.get("version_id"),
        )
        module.exit_json(changed=changed, **result)


def populate_params(module: AnsibleAWSModule) -> Dict:
    # Copy the parameters dict, we shouldn't be directly modifying it.
    variable_dict = copy.deepcopy(module.params)

    if variable_dict["validate_bucket_name"]:
        validate_bucket_name(variable_dict["bucket"])

    if variable_dict.get("overwrite") == "different" and not HAS_MD5:
        module.fail_json(msg="overwrite=different is unavailable: ETag calculation requires MD5 support")

    if variable_dict.get("overwrite") not in [
        "always",
        "never",
        "different",
        "latest",
    ]:
        if module.boolean(variable_dict["overwrite"]):
            variable_dict["overwrite"] = "always"
        else:
            variable_dict["overwrite"] = "never"

    # Bucket deletion does not require obj.  Prevents ambiguity with delobj.
    if variable_dict["object"]:
        if variable_dict.get("mode") == "delete":
            module.fail_json(msg="Parameter object cannot be used with mode=delete")
        obj = variable_dict["object"]
        if obj.startswith("/"):
            module.fail_json(
                msg="Parameter 'object' should not start with a leading '/'. See https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html"
            )

    variable_dict["validate"] = not variable_dict["ignore_nonexistent_bucket"]
    variable_dict["acl_disabled"] = False

    return variable_dict


def validate_bucket(module: AnsibleAWSModule, s3: ClientType, var_dict: Dict) -> Dict:
    bucket_check(module, s3, var_dict["bucket"], validate=var_dict["validate"])

    try:
        ownership_controls = get_s3_bucket_ownership_controls(s3, var_dict["bucket"])
        if ownership_controls and ownership_controls.get("Rules"):
            object_ownership = ownership_controls["Rules"][0]["ObjectOwnership"]
            if object_ownership == "BucketOwnerEnforced":
                var_dict["acl_disabled"] = True
    except AnsibleS3Error:
        # Bucket ownership controls not found or not accessible
        pass

    if not var_dict["acl_disabled"]:
        var_dict["object_acl"] = list(var_dict.get("permission"))

    return var_dict


def main():
    # Beware: this module uses an action plugin (plugins/action/s3_object.py)
    # so that src parameter can be either in 'files/' lookup path on the
    # controller, *or* on the remote host that the task is executed on.

    valid_modes = ["get", "put", "create", "geturl", "getstr", "delobj", "list", "copy"]
    valid_acls = [
        "private",
        "public-read",
        "public-read-write",
        "aws-exec-read",
        "authenticated-read",
        "bucket-owner-read",
        "bucket-owner-full-control",
    ]

    argument_spec = dict(
        bucket=dict(required=True),
        dest=dict(default=None, type="path"),
        encrypt=dict(default=True, type="bool"),
        encryption_mode=dict(choices=["AES256", "aws:kms"], default="AES256"),
        expiry=dict(default=600, type="int", aliases=["expiration"]),
        headers=dict(type="dict"),
        marker=dict(),
        max_keys=dict(type="int", no_log=False),
        metadata=dict(type="dict"),
        mode=dict(choices=valid_modes, required=True),
        sig_v4=dict(default=True, type="bool"),
        object=dict(),
        permission=dict(type="list", elements="str", default=["private"], choices=valid_acls),
        version=dict(default=None),
        overwrite=dict(aliases=["force"], default="different"),
        prefix=dict(default=""),
        retries=dict(aliases=["retry"], type="int", default=0),
        dualstack=dict(default=False, type="bool"),
        ceph=dict(default=False, type="bool", aliases=["rgw"]),
        src=dict(type="path"),
        content=dict(),
        content_base64=dict(),
        ignore_nonexistent_bucket=dict(default=False, type="bool"),
        encryption_kms_key_id=dict(),
        tags=dict(type="dict", aliases=["resource_tags"]),
        purge_tags=dict(type="bool", default=True),
        copy_src=dict(
            type="dict",
            options=dict(
                bucket=dict(required=True),
                object=dict(),
                prefix=dict(default=""),
                version_id=dict(),
            ),
        ),
        validate_bucket_name=dict(type="bool", default=True),
        expected_bucket_owner=dict(type="str"),
    )

    required_if = [
        ["ceph", True, ["endpoint_url"]],
        ["mode", "put", ["object"]],
        ["mode", "put", ["content", "content_base64", "src"], True],
        ["mode", "create", ["object"]],
        ["mode", "get", ["dest", "object"]],
        ["mode", "getstr", ["object"]],
        ["mode", "geturl", ["object"]],
        ["mode", "copy", ["copy_src"]],
        ["mode", "delobj", ["object"]],
    ]

    module = AnsibleAWSModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=required_if,
        mutually_exclusive=[["content", "content_base64", "src"]],
    )

    if module.params.get("mode") == "list":
        module.deprecate(
            (
                "Support for 'list' mode has been deprecated and will be removed in a release after "
                "2026-11-01.  Please use the amazon.aws.s3_object_info module instead."
            ),
            date="2026-11-01",
            collection_name="amazon.aws",
        )

    endpoint_url = module.params.get("endpoint_url")
    dualstack = module.params.get("dualstack")

    if dualstack and endpoint_url:
        module.deprecate(
            (
                "Support for passing both the 'dualstack' and 'endpoint_url' parameters at the same "
                "time has been deprecated."
            ),
            date="2024-12-01",
            collection_name="amazon.aws",
        )
        if "amazonaws.com" not in endpoint_url:
            module.fail_json(msg="dualstack only applies to AWS S3")

    if module.params.get("overwrite") not in ("always", "never", "different", "latest"):
        module.deprecate(
            (
                "Support for passing values of 'overwrite' other than 'always', 'never', "
                "'different' or 'latest', has been deprecated."
            ),
            date="2024-12-01",
            collection_name="amazon.aws",
        )

    extra_params = s3_extra_params(module.params, sigv4=False)
    extra_params_v4 = s3_extra_params(module.params, sigv4=True)
    retry_decorator = AWSRetry.jittered_backoff()
    s3 = module.client("s3", retry_decorator=retry_decorator, **extra_params)
    s3_v4 = module.client("s3", retry_decorator=retry_decorator, **extra_params_v4)

    s3_object_params = populate_params(module)
    s3_object_params.update(validate_bucket(module, s3, s3_object_params))

    # Conditions that force the use of Sig V4
    if module.params.get("sig_v4"):
        s3 = s3_v4
    if module.params.get("encryption_mode") == "aws:kms":
        s3 = s3_v4

    func_mapping = {
        "get": do_s3_object_get,
        "put": do_s3_object_put,
        "delobj": do_s3_object_delobj,
        "list": do_s3_object_list,
        "create": do_s3_object_create,
        "geturl": do_s3_object_geturl,
        "getstr": do_s3_object_getstr,
        "copy": do_s3_object_copy,
    }
    func = func_mapping[s3_object_params["mode"]]
    try:
        try:
            func(module, s3, s3_object_params)
        except AnsibleS3Sigv4RequiredError:
            # Opportunistically bump the connection up to SigV4
            func(module, s3_v4, s3_object_params)
    except AnsibleS3Error as e:
        module.fail_json_aws_error(e)

    module.exit_json(failed=False)


if __name__ == "__main__":
    main()
