"""
Presigned URL helper for File records.

Generates a time-limited S3 presigned URL for a file stored in S3.
Falls back to the file's full_url when S3 is not the active CDN.
Never raises — returns None on any failure.
"""
import logging
from typing import Optional

logger = logging.getLogger(__name__)


def generate_presigned_file_url(
    file,
    expiry_seconds: int = 3600,
    db=None,
) -> Optional[str]:
    """
    Return a signed/accessible URL for the given File ORM record.

    - S3 CDN: generates a boto3 presigned URL with the specified TTL.
    - Local CDN / fallback: returns file.full_url directly.
    - Returns None if file is None or URL generation fails.

    Args:
        file:           File ORM instance (must have storage_key and/or full_url).
        expiry_seconds: Presigned URL lifetime in seconds (default 3600 = 1 hour).
        db:             Optional SQLAlchemy Session. When provided, it is reused
                        to resolve the active CDN (avoids opening a second
                        connection). When None, a short-lived session is opened.

    Returns:
        A URL string, or None.
    """
    if file is None:
        return None
    try:
        from src.apps.base.services import get_active_cdn
        from src.core.config import settings

        if db is not None:
            cdn = get_active_cdn(db)
        else:
            # Fallback: open a dedicated short-lived session only when no
            # session is supplied (e.g. called from the presigned-url endpoint).
            from src.core.database import SessionLocal
            _db = SessionLocal()
            try:
                cdn = get_active_cdn(_db)
            finally:
                _db.close()

        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: return the file's public/full URL
        full_url = getattr(file, "full_url", None)
        if full_url:
            return full_url

        # Last resort: construct 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 exc:
        logger.error("Presigned URL generation failed for file %s: %s", getattr(file, "id", "?"), exc)
        return None
