"""
Avatar URL generation helper — handles both S3 presigned URLs and local CDN URLs.
Never raises — returns None on any failure.
"""
import logging
from typing import Optional

from sqlalchemy.orm import Session

logger = logging.getLogger(__name__)


def generate_avatar_signed_url(file, db: Session, expiry_seconds: int = 3600) -> Optional[str]:
    """
    Returns a signed/accessible URL for the avatar file.
    - S3 CDN: boto3 presigned URL with 1-hour TTL
    - Local CDN: returns file.full_url directly
    - Returns None if file is None
    """
    if file is None:
        return None
    try:
        from src.apps.base.services import get_active_cdn
        from src.core.config import settings

        cdn = get_active_cdn(db)
        if cdn and cdn.label and cdn.label.lower() == "s3":
            storage_key = getattr(file, "storage_key", None)
            if storage_key:
                import boto3
                s3 = boto3.client(
                    "s3",
                    aws_access_key_id=settings.AWS_S3_ACCESS_KEY,
                    aws_secret_access_key=settings.AWS_S3_SECRET_KEY,
                    region_name=getattr(settings, "AWS_S3_REGION", "us-east-1"),
                )
                return s3.generate_presigned_url(
                    "get_object",
                    Params={
                        "Bucket": settings.AWS_S3_DEFAULT_BUCKET,
                        "Key": storage_key,
                    },
                    ExpiresIn=expiry_seconds,
                )

        # Fallback: use full_url or construct from path
        full_url = getattr(file, "full_url", None)
        if full_url:
            return full_url

        # Last resort: build from path and settings
        path = getattr(file, "path", None)
        if path:
            from src.core.config import settings as cfg
            return f"{cfg.SERVER_HOST}{cfg.STATIC_FILES_PATH}/{path.lstrip('/')}"

        return None
    except Exception as e:
        logger.error(f"Avatar URL generation failed: {e}")
        return None
