from fastapi import APIRouter, File, Form, HTTPException, Query, Response, UploadFile
from pydantic import BaseModel, Field

from app.services.data_management_service import DataManagementService
from app.utils.response import success_response


router = APIRouter()
service = DataManagementService()


class CategoryCreateRequest(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    parent_id: str | int | None = Field(default='all')


class CategoryUpdateRequest(BaseModel):
    name: str = Field(min_length=1, max_length=100)


@router.get('/categories')
def get_categories():
    return success_response(data=service.get_category_tree())


@router.post('/categories')
def create_category(request: CategoryCreateRequest):
    try:
        parent_id = 'all' if request.parent_id is None else str(request.parent_id)
        category = service.create_category(name=request.name.strip(), parent_id=parent_id)
        return success_response(data=category, message='分类创建成功')
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error)) from error


@router.put('/categories/{category_id}')
def update_category(category_id: str, request: CategoryUpdateRequest):
    try:
        category = service.update_category(category_id=category_id, name=request.name.strip())
        return success_response(data=category, message='分类更新成功')
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error)) from error


@router.delete('/categories/{category_id}')
def delete_category(category_id: str):
    try:
        service.delete_category(category_id=category_id)
        return success_response(data=True, message='分类删除成功')
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error)) from error


@router.get('/files')
def get_files(
    category_id: str = Query(default=''),
    filename: str = Query(default=''),
):
    return success_response(data=service.list_files(category_id=category_id, filename=filename.strip()))


@router.post('/files/upload')
async def upload_file(
    file: UploadFile = File(...),
    category_id: str = Form(default=''),
):
    try:
        content = await file.read()
        if not content:
            raise ValueError('上传文件为空')

        file_meta = service.upload_file(
            filename=file.filename or 'unknown.xlsx',
            content=content,
            category_id=category_id,
        )
        return success_response(data=file_meta, message='文件上传成功')
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error)) from error


@router.get('/files/template')
def download_template():
    content = service.get_excel_template_bytes()
    return Response(
        content=content,
        media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        headers={
            'Content-Disposition': 'attachment; filename=data_template.xlsx',
        },
    )


@router.delete('/files/{file_id}')
def delete_file(file_id: str):
    try:
        service.delete_file(file_id=file_id)
        return success_response(data=True, message='文件删除成功')
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error)) from error


@router.get('/files/{file_id}/records')
def get_file_records(file_id: str, limit: int = Query(default=500, ge=1, le=5000)):
    try:
        result = service.get_file_records(file_id=file_id, limit=limit)
        return success_response(data=result)
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error)) from error
