# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt

"""
提供对云端数据库的增删改查操作
"""

from fastapi import APIRouter, HTTPException, Request, UploadFile, File, Form
from fastapi.responses import JSONResponse
from typing import Dict, Any, Optional
import json
import jingrow

router = APIRouter()


@router.get("/api/data/{pagetype}")
async def get_records(
    request: Request,
    pagetype: str,
    fields: Optional[str] = None,
    filters: Optional[str] = None,
    order_by: str = "modified desc",
    limit_start: int = 0,
    limit_page_length: int = 20
):
    """获取记录列表"""
    try:
        try:
            fields_list = json.loads(fields) if fields else []
        except Exception:
            raise
        try:
            filters_list = json.loads(filters) if filters else []
        except Exception:
            raise
        
        if limit_page_length == 0:
            limit = None
        else:
            limit = limit_start + limit_page_length
        
        try:
            data = jingrow.get_list(
                pagetype=pagetype,
                filters=filters_list,
                fields=fields_list,
                limit=limit
            )
        except Exception:
            raise

        if not isinstance(data, list):
            raise HTTPException(status_code=400, detail='获取记录列表失败')

        if limit_page_length > 0:
            if limit_start > 0:
                data = data[limit_start:]
            data = data[:limit_page_length]

        estimated_total = limit_start + len(data)
        if limit_page_length > 0 and len(data) < limit_page_length:
            estimated_total = limit_start + len(data)
        elif limit_page_length > 0:
            estimated_total = limit_start + limit_page_length + 1

        return JSONResponse(content={
            "data": data,
            "total": estimated_total
        })
            
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/api/data/{pagetype}/{name}")
async def get_record_api(request: Request, pagetype: str, name: str):
    """获取单个记录"""
    try:
        data = jingrow.get_pg(pagetype, name)
        if data is None:
            raise HTTPException(status_code=404, detail='记录不存在')
        return JSONResponse(content={"data": data})
            
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/api/data/{pagetype}")
async def create_record_api(request: Request, pagetype: str, data: Dict[str, Any]):
    """创建记录"""
    try:
        created_data = jingrow.create_pg(pagetype, data) or {}
        if not isinstance(created_data, dict):
            raise HTTPException(status_code=400, detail='创建记录失败')
        
        return JSONResponse(content={
            "message": "Created successfully",
            "data": created_data
        })
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/api/data/{pagetype}/{name}")
async def update_record_api(request: Request, pagetype: str, name: str, data: Dict[str, Any]):
    """更新记录"""
    try:
        updated = jingrow.update_pg(pagetype, name, data)
        if updated is False:
            raise HTTPException(status_code=400, detail='更新记录失败')
        return JSONResponse(content={
            "message": "Updated successfully",
            "data": (updated or {}) if isinstance(updated, dict) else {}
        })
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/api/data/{pagetype}/{name}")
async def delete_record_api(request: Request, pagetype: str, name: str):
    """删除记录"""
    try:
        ok = jingrow.delete_pg(pagetype, name)
        if not ok:
            raise HTTPException(status_code=400, detail='删除记录失败')
        
        return JSONResponse(content={
            "message": "Deleted successfully"
        })
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/jingrow/bulk-delete")
async def batch_delete_records(request: Request, data: Dict[str, Any]):
    """批量删除记录"""
    pagetype = data.get('pagetype')
    name = data.get('name')
    names = data.get('names', [])
    
    if not pagetype:
        raise HTTPException(status_code=400, detail="缺少必要参数 pagetype")
    
    # 统一处理：如果提供了单个 name，转换为列表
    if name and not names:
        names = [name]
    
    if not names:
        raise HTTPException(status_code=400, detail="缺少必要参数 name 或 names")
    
    # 批量删除
    success_count = 0
    failed_names = []
    
    for name_item in names:
        try:
            if jingrow.delete_pg(pagetype, name_item):
                success_count += 1
            else:
                failed_names.append(name_item)
        except Exception:
            failed_names.append(name_item)
    
    failed_count = len(failed_names)
    
    # 根据结果返回响应
    if failed_count == 0:
        return JSONResponse(content={
            "message": f"成功删除 {success_count} 条记录",
            "success_count": success_count,
            "failed_count": 0
        })
    elif success_count > 0:
        return JSONResponse(content={
            "message": f"部分删除成功：{success_count} 条成功，{failed_count} 条失败",
            "success_count": success_count,
            "failed_count": failed_count,
            "failed_names": failed_names
        }, status_code=207)  # 207 Multi-Status
    else:
        raise HTTPException(status_code=400, detail="所有记录删除失败")

@router.post("/jingrow/get-count")
async def get_record_count(request: Request, pagetype: str):
    """获取记录总数"""
    try:
        count = jingrow.get_count(pagetype)
        return JSONResponse(content={"message": count})
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/jingrow/upload_file")
async def upload_file_api(
    file: UploadFile = File(...),
    attached_to_pagetype: Optional[str] = Form(None),
    attached_to_name: Optional[str] = Form(None),
    attached_to_field: Optional[str] = Form(None)
):
    """上传文件到Jingrow服务器"""
    try:
        # 读取文件内容
        file_content = await file.read()
        filename = file.filename or "uploaded_file"
        
        # 调用 jingrow.upload_file
        result = jingrow.upload_file(
            file_data=file_content,
            filename=filename,
            attached_to_pagetype=attached_to_pagetype,
            attached_to_name=attached_to_name,
            attached_to_field=attached_to_field
        )
        
        # 检查结果
        if result.get('success'):
            return JSONResponse(content={
                "message": {
                    "file_url": result.get('file_url'),
                    "file_name": result.get('file_name')
                }
            })
        else:
            raise HTTPException(status_code=400, detail=result.get('error', '上传文件失败'))
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/jingrow/get-module-app")
async def get_module_app_api(request: Request, pagetype: str):
    """获取指定 pagetype 的模块应用信息"""
    try:
        result = jingrow.get_module_app(pagetype)
        
        # 检查结果格式
        if not isinstance(result, dict):
            raise HTTPException(status_code=500, detail='获取模块应用信息失败：返回格式错误')
        
        if result.get('success'):
            return JSONResponse(content={
                "message": {
                    "success": True,
                    "module": result.get('module'),
                    "app": result.get('app'),
                    "pagetype": pagetype
                }
            })
        else:
            error_msg = result.get('error', '获取模块应用信息失败')
            raise HTTPException(status_code=400, detail=error_msg)
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
