import logging
import time

from pyramid.view import view_config

from . import user_required

log = logging.getLogger(__name__)


@view_config(route_name="user_sandbox_upload", renderer="json", request_method="POST")
@user_required()
def sandbox_presign(request):
    """Generate a presigned POST for uploading a sandbox artifact to the user's S3 bucket.

    The browser sends filename and content_type. This endpoint creates a boto3
    client with the user's stored credentials, generates a presigned POST, and
    returns the URL + fields. The browser then uploads the blob directly to the
    user's bucket — the file never touches the MPS server.
    """
    user = request.user

    if not user.has_s3_bucket:
        request.response.status_code = 400
        return {"error": "No S3 bucket configured. Go to User Settings > Artifact Storage."}

    filename = request.params.get("filename", "sandbox-export.png").strip()
    content_type = request.params.get("content_type", "image/png").strip()

    # Sanitize filename — keep only safe characters
    safe_filename = "".join(
        c for c in filename if c.isalnum() or c in ".-_"
    ) or "sandbox-export"

    # Build S3 key: sandbox/{user_id}/{timestamp}-{filename}
    key = "sandbox/{}/{}-{}".format(user.uuid_str, int(time.time()), safe_filename)

    try:
        import boto3

        session = boto3.session.Session()
        client = session.client(
            "s3",
            region_name=user.s3_region or "us-east-1",
            endpoint_url=user.s3_endpoint,
            aws_access_key_id=user.s3_access_key,
            aws_secret_access_key=user.s3_secret_key,
        )

        presigned = client.generate_presigned_post(
            Bucket=user.s3_bucket,
            Key=key,
            ExpiresIn=900,
            Conditions=[
                ["content-length-range", 1, 50 * 1024 * 1024],  # 50MB max
            ],
            Fields={"Content-Type": content_type},
        )

        return {"presigned": presigned, "key": key}

    except Exception as e:
        log.warning("sandbox_presign failed for user %s: %s", user.uuid_str, e)
        request.response.status_code = 500
        return {"error": "Failed to generate upload URL. Check your S3 credentials."}
