import os
import boto3
from dotenv import load_dotenv

load_dotenv()

AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY")
AWS_SECRET_KEY = os.getenv("AWS_SECRET_KEY")
AWS_REGION = os.getenv("AWS_REGION")
BUCKET_NAME = os.getenv("BUCKET_NAME")

s3_client = boto3.client(
    "s3",
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY,
    region_name=AWS_REGION,
)

def list_pdfs_in_prefix(prefix: str):
    """List all PDFs in the given S3 prefix."""
    response = s3_client.list_objects_v2(Bucket=BUCKET_NAME, Prefix=prefix)
    if "Contents" not in response:
        return []
    return [obj["Key"] for obj in response["Contents"] if obj["Key"].endswith(".pdf")]

def download_pdf(key: str, dest_path: str):
    """Download a PDF from S3 to local path."""
    os.makedirs(os.path.dirname(dest_path), exist_ok=True)
    s3_client.download_file(BUCKET_NAME, key, dest_path)
    return dest_path
