"""S3-compatible object storage service (Scaleway)."""

from contextlib import suppress
from typing import Any

import boto3
from botocore.config import Config as BotoConfig

from app.config import get_settings

_client = None


def _get_client() -> Any:
    global _client
    if _client is None:
        settings = get_settings()
        if not settings.S3_ENDPOINT_URL:
            raise RuntimeError("S3 storage not configured: set S3_ENDPOINT_URL")
        _client = boto3.client(
            "s3",
            endpoint_url=settings.S3_ENDPOINT_URL,
            aws_access_key_id=settings.S3_ACCESS_KEY_ID,
            aws_secret_access_key=settings.S3_SECRET_ACCESS_KEY,
            region_name=settings.S3_REGION,
            config=BotoConfig(signature_version="s3v4"),
        )
    return _client


def upload_file(data: bytes, key: str, content_type: str) -> str:
    """Upload bytes to S3 and return the public URL."""
    settings = get_settings()
    client = _get_client()
    client.put_object(
        Bucket=settings.S3_BUCKET_NAME,
        Key=key,
        Body=data,
        ContentType=content_type,
        ACL="public-read",
    )
    return f"{settings.S3_ENDPOINT_URL}/{settings.S3_BUCKET_NAME}/{key}"


def delete_file(key: str) -> None:
    """Delete a file from S3. No-op if not found."""
    settings = get_settings()
    client = _get_client()
    with suppress(Exception):
        client.delete_object(
            Bucket=settings.S3_BUCKET_NAME,
            Key=key,
        )


def key_from_url(url: str) -> str | None:
    """Extract S3 key from a full URL. Returns None for non-S3 URLs."""
    settings = get_settings()
    prefix = f"{settings.S3_ENDPOINT_URL}/{settings.S3_BUCKET_NAME}/"
    if url.startswith(prefix):
        return url[len(prefix) :]
    return None
