"""
Cross-bucket S3 helper for ingesting files from the Daedalus S3 bucket
into Mnemosyne's own bucket.

Daedalus uploads files to its own bucket (configured per Daedalus deployment)
and posts an ingest request to Mnemosyne with the s3_key. This module fetches
that file using read-only Daedalus credentials and writes it to Mnemosyne's
bucket via the standard `default_storage` backend so the rest of the pipeline
(parsing, chunking, embedding) works unchanged.
"""

import logging

import boto3
from django.conf import settings
from django.core.files.base import ContentFile
from django.core.files.storage import default_storage

logger = logging.getLogger(__name__)


def _daedalus_s3_client():
    """Build a boto3 S3 client pointed at the Daedalus bucket."""
    return boto3.client(
        "s3",
        endpoint_url=settings.DAEDALUS_S3_ENDPOINT_URL or None,
        aws_access_key_id=settings.DAEDALUS_S3_ACCESS_KEY_ID,
        aws_secret_access_key=settings.DAEDALUS_S3_SECRET_ACCESS_KEY,
        region_name=settings.DAEDALUS_S3_REGION_NAME,
        use_ssl=settings.DAEDALUS_S3_USE_SSL,
        verify=settings.DAEDALUS_S3_VERIFY,
    )


def fetch_from_daedalus(daedalus_s3_key: str) -> bytes:
    """
    Read a file from the Daedalus S3 bucket.

    :param daedalus_s3_key: Object key in the Daedalus bucket.
    :returns: File bytes.
    :raises: botocore exceptions on failure (caller decides retry).
    """
    client = _daedalus_s3_client()
    bucket = settings.DAEDALUS_S3_BUCKET_NAME
    logger.debug(
        "Fetching from Daedalus S3 bucket=%s key=%s", bucket, daedalus_s3_key
    )
    response = client.get_object(Bucket=bucket, Key=daedalus_s3_key)
    data = response["Body"].read()
    logger.info(
        "Fetched from Daedalus S3 bucket=%s key=%s size=%d",
        bucket, daedalus_s3_key, len(data),
    )
    return data


def copy_into_mnemosyne(data: bytes, mnemosyne_s3_key: str) -> str:
    """
    Write bytes into Mnemosyne's S3 bucket via the default_storage backend.

    :param data: File bytes (already in memory).
    :param mnemosyne_s3_key: Target object key in Mnemosyne's bucket.
    :returns: The actual key written (may differ from requested if
              `file_overwrite=False` and the key existed).
    """
    saved_key = default_storage.save(mnemosyne_s3_key, ContentFile(data))
    logger.info(
        "Wrote to Mnemosyne S3 key=%s size=%d", saved_key, len(data),
    )
    return saved_key
