"""
Media Library REST API
POST   /api/media/upload          — upload ảnh/video
GET    /api/media                  — list assets
GET    /api/media/{id}             — serve raw file
GET    /api/media/{id}/thumb       — serve thumbnail
GET    /api/media/{id}/info        — asset metadata
DELETE /api/media/{id}             — xóa asset
GET    /api/media/platforms        — list platform sizes
POST   /api/media/{id}/resize      — resize theo platform
"""

import logging
import os

from fastapi import APIRouter, File, HTTPException, Query, UploadFile
from fastapi.responses import FileResponse

from common.media.image_processor import (PLATFORM_SIZES, delete_asset, get_asset, list_assets, resize_for_platform,
                                          save_uploaded_asset)

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/media", tags=["Media Library"])

ALLOWED_CONTENT_TYPES = {
    "image/jpeg", "image/jpg", "image/png", "image/webp", "image/gif",
    "video/mp4", "video/quicktime", "video/webm",
}
MAX_FILE_SIZE = 50 * 1024 * 1024  # 50MB


@router.post("/upload")
async def upload_asset(
    file: UploadFile = File(...),
    tags: str = Query("", description="Comma-separated tags"),
    uploaded_by: str = Query("user"),
):
    """Upload ảnh hoặc video vào media library."""
    if file.content_type not in ALLOWED_CONTENT_TYPES:
        raise HTTPException(
            status_code=415,
            detail=f"Unsupported file type: {file.content_type}. Allowed: {', '.join(ALLOWED_CONTENT_TYPES)}",
        )

    content = await file.read()
    if len(content) > MAX_FILE_SIZE:
        raise HTTPException(status_code=413, detail="File quá lớn (max 50MB)")

    tag_list = [t.strip() for t in tags.split(",") if t.strip()] if tags else []

    asset = save_uploaded_asset(
        filename=file.filename or "upload",
        content_bytes=content,
        content_type=file.content_type,
        uploaded_by=uploaded_by,
        tags=tag_list,
    )

    return {"ok": True, "asset": asset}


@router.get("")
async def list_media(
    content_type: str = Query(None, description="Filter: 'image' or 'video'"),
    tag: str = Query(None),
    limit: int = 50,
    offset: int = 0,
):
    """List tất cả assets trong media library."""
    return list_assets(content_type=content_type, tag=tag, limit=limit, offset=offset)


@router.get("/platforms")
async def platform_sizes():
    """Danh sách platform sizes để resize."""
    return {
        "platforms": [
            {"key": k, "width": v[0], "height": v[1]}
            for k, v in PLATFORM_SIZES.items()
        ]
    }


@router.get("/{asset_id}/info")
async def asset_info(asset_id: str):
    """Lấy metadata của asset."""
    asset = get_asset(asset_id)
    if not asset:
        raise HTTPException(status_code=404, detail="Asset not found")
    return asset


@router.get("/{asset_id}")
async def serve_asset(asset_id: str):
    """Serve file raw."""
    asset = get_asset(asset_id)
    if not asset:
        raise HTTPException(status_code=404, detail="Asset not found")
    path = asset.get("path", "")
    if not os.path.exists(path):
        raise HTTPException(status_code=404, detail="File not found on disk")
    return FileResponse(path, media_type=asset.get("content_type", "application/octet-stream"))


@router.get("/{asset_id}/thumb")
async def serve_thumbnail(asset_id: str):
    """Serve thumbnail image."""
    asset = get_asset(asset_id)
    if not asset:
        raise HTTPException(status_code=404, detail="Asset not found")
    thumb_path = asset.get("thumb_path", "")
    if not thumb_path or not os.path.exists(thumb_path):
        # Fallback to original
        return await serve_asset(asset_id)
    return FileResponse(thumb_path, media_type="image/jpeg")


@router.post("/{asset_id}/resize")
async def resize_asset(asset_id: str, platform: str):
    """Resize asset theo platform spec. Returns resized image bytes."""
    from fastapi.responses import Response

    asset = get_asset(asset_id)
    if not asset:
        raise HTTPException(status_code=404, detail="Asset not found")

    if platform not in PLATFORM_SIZES:
        raise HTTPException(
            status_code=400,
            detail=f"Unknown platform: {platform}. Available: {list(PLATFORM_SIZES.keys())}",
        )

    path = asset.get("path", "")
    if not os.path.exists(path):
        raise HTTPException(status_code=404, detail="File not found on disk")

    with open(path, "rb") as f:
        content_bytes = f.read()

    resized = resize_for_platform(content_bytes, platform)
    size = PLATFORM_SIZES[platform]
    return Response(
        content=resized,
        media_type="image/jpeg",
        headers={
            "Content-Disposition": f'inline; filename="{asset_id}_{platform}.jpg"',
            "X-Dimensions": f"{size[0]}x{size[1]}",
        },
    )


@router.delete("/{asset_id}")
async def delete_media_asset(asset_id: str):
    """Xóa asset khỏi library."""
    ok = delete_asset(asset_id)
    if not ok:
        raise HTTPException(status_code=404, detail="Asset not found")
    return {"ok": True}
