import os
import boto3

from botocore.exceptions import ClientError
from fastapi.responses import StreamingResponse
from src.core.auth import require_enterprise_or_front
from fastapi import APIRouter, UploadFile, File, HTTPException, Depends

router = APIRouter()

BUKCET = os.getenv("BUCKET")
BUCKET_ENDPOINT = os.getenv("BUCKET_ENDPOINT")
BUCKET_KEY_ID = os.getenv("BUCKET_KEY_ID")
BUCKET_APP_KEY = os.getenv("BUCKET_APP_KEY")
BUCKET_FOLDER = os.getenv("BUCKET_FOLDER")

ALLOWED_TYPES = {
    "image/jpeg",
    "image/png",
    "image/gif",
    "image/webp",
    "image/jpg",
}

MAX_SIZE = 5 * 1024 * 1024

s3_client = boto3.client(
    "s3",
    endpoint_url=f"https://{BUCKET_ENDPOINT}",
    aws_access_key_id=BUCKET_KEY_ID,
    aws_secret_access_key=BUCKET_APP_KEY,
    region_name="us-east-005",
)


@router.post("/upload")
async def upload_image(
    file: UploadFile = File(...),
        _auth: dict = Depends(require_enterprise_or_front)
):
    """
    Upload de imagem para Backblaze B2

    Retorna a URL pública da imagem
    """
    try:
        if file.content_type not in ALLOWED_TYPES:
            raise HTTPException(
                status_code=400,
                detail=(
                    "Tipo de arquivo inválido. Permitidos: "
                    f"{', '.join(ALLOWED_TYPES)}"
                ),
            )

        content = await file.read()

        if len(content) > MAX_SIZE:
            raise HTTPException(
                status_code=413,
                detail="Arquivo muito grande. Máximo 5MB."
            )

        import time
        timestamp = int(time.time() * 1000)
        file_extension = file.filename.split(
            ".")[-1] if "." in file.filename else "jpg"
        s3_key = f"{BUCKET_FOLDER}/{timestamp}.{file_extension}"

        s3_client.put_object(
            Bucket=BUKCET,
            Key=s3_key,
            Body=content,
            ContentType=file.content_type,
        )

        public_url = f"https://{BUCKET_ENDPOINT}/file/{BUKCET}/{s3_key}"

        return {
            "success": True,
            "url": public_url,
            "key": s3_key,
            "fileName": file.filename,
            "size": len(content),
                }

    except HTTPException:
        raise
    except ClientError:
        raise HTTPException(
            status_code=500,
            detail="Erro ao fazer upload no armazenamento"
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )


@router.get("/images/{folder}/{filename}")
async def download_image(
    folder: str,
    filename: str,
    _auth: dict = Depends(require_enterprise_or_front)
):
    """
    Download/visualizar imagem da bucket

    Exemplo: GET /api/images/screenshots-pomind/1234567890.jpg
    """
    try:
        file_key = f"{folder}/{filename}"

        response = s3_client.get_object(
            Bucket=BUKCET,
            Key=file_key
        )

        return StreamingResponse(
            response["Body"].iter_chunks(),
            media_type=response["ContentType"],
            headers={
                "Content-Disposition": f'inline; filename="{filename}"'
            }
        )

    except ClientError as e:
        error_code = e.response['Error']['Code']
        if error_code == "NoSuchKey":
            raise HTTPException(
                status_code=404,
                detail="Imagem não encontrada"
            )
        raise HTTPException(
            status_code=500,
            detail="Erro ao obter imagem"
        )
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=str(e)
        )
