"""Avatars – full CRUD with file upload."""
import os, uuid
from typing import Optional
from fastapi import APIRouter, Depends, Query, UploadFile, File, Form
from app.middleware.auth import require_auth
from app.repository.store import avatars_store
from app.schemas.schemas import AvatarUpdate
from app.utils.response import ok, err
from app.config import cfg

router = APIRouter()


@router.get("/")
async def list_avatars(
    page: int = Query(1, ge=1),
    per_page: int = Query(12, ge=1, le=100),
    search: Optional[str] = Query(None),
    status: Optional[str] = Query(None),
    _: str = Depends(require_auth),
):
    filters = {"status": status} if status else None
    result = avatars_store.list(
        filters=filters, search=search,
        search_fields=["name", "description"],
        page=page, per_page=per_page,
    )
    return ok(result)


@router.post("/")
async def create_avatar(
    name: str = Form(...),
    description: str = Form(""),
    source_type: str = Form("photo"),
    voice_engine: str = Form("openai"),
    voice_gender: str = Form("female"),
    face_engine: str = Form("liveportrait"),
    lip_engine: str = Form("wav2lip"),
    enhance: bool = Form(True),
    tags: str = Form(""),
    file: Optional[UploadFile] = File(None),
    _: str = Depends(require_auth),
):
    file_url = None
    if file:
        ext = os.path.splitext(file.filename or "")[1]
        fname = f"{uuid.uuid4()}{ext}"
        dest = os.path.join(cfg.UPLOAD_DIR, fname)
        os.makedirs(cfg.UPLOAD_DIR, exist_ok=True)
        content = await file.read()
        if len(content) > 100 * 1024 * 1024:
            return err("File too large (max 100MB)")
        with open(dest, "wb") as f_out:
            f_out.write(content)
        file_url = f"/uploads/{fname}"

    avatar = avatars_store.create({
        "name": name,
        "description": description,
        "source_type": source_type,
        "voice_engine": voice_engine,
        "voice_gender": voice_gender,
        "face_engine": face_engine,
        "lip_engine": lip_engine,
        "enhance": enhance,
        "tags": [t.strip() for t in tags.split(",") if t.strip()],
        "status": "ready",
        "source_url": file_url,
        "thumbnail_url": None,
        "video_count": 0,
    })
    return ok(avatar, "Avatar created")


@router.get("/{avatar_id}")
async def get_avatar(avatar_id: str, _: str = Depends(require_auth)):
    av = avatars_store.get(avatar_id)
    if not av:
        return err("Avatar not found", 404)
    return ok(av)


@router.put("/{avatar_id}")
async def update_avatar(avatar_id: str, body: AvatarUpdate, _: str = Depends(require_auth)):
    updates = {k: v for k, v in body.model_dump().items() if v is not None}
    av = avatars_store.update(avatar_id, updates)
    if not av:
        return err("Avatar not found", 404)
    return ok(av, "Avatar updated")


@router.delete("/{avatar_id}")
async def delete_avatar(avatar_id: str, _: str = Depends(require_auth)):
    if not avatars_store.delete(avatar_id):
        return err("Avatar not found", 404)
    return ok(None, "Avatar deleted")
