from fastapi import APIRouter, Depends, HTTPException, UploadFile
from sqlalchemy.orm import Session
from sqlalchemy.sql import select, or_, and_, func,distinct
from db.schemas  import KgTask,KgProj,KgProjCreate,KgTaskCreate,KgTaskUpdate
from db.models import DbKgProj,DbKgTask
from db.database import  get_db
from models.response import ResponseModel
from utils.response import resp_200
from typing import List
from datetime import datetime
from math import ceil
from config.site import FILE_STORAGE_PATH
import os
import json

router = APIRouter()

def create_task( proj_id, task_category, content: str,db:Session):
    data = DbKgTask()
    data.proj_id = proj_id
    data.task_category = task_category
    data.task_log = ""
    data.task_content = content
    data.status = 0
    data.created = datetime.now()
    data.updated = datetime.now()    
    db.add(data)
    db.commit()
    db.refresh(data)  
    return data 

#获取所有标注项目
@router.get("/api/proj-all")
def get_all_projects(db: Session = Depends(get_db)):
    result = db.query(DbKgProj).filter(DbKgProj.status>=0, DbKgProj.proj_category=='LABELING').all()
    data = [KgProj.model_validate(item) for item in result]

    projs = [d.model_dump() for d in data]
    for proj in projs:
        proj.pop("proj_conf")
    return resp_200(data={'records': projs})


#搜索标注项目
@router.get("/api/proj-search/{proj_category}/{query}")
def search_projects(proj_category:str, query:str, db: Session = Depends(get_db)):
    result = db.query(DbKgProj).filter(DbKgProj.status>=0,
                                       DbKgProj.proj_category==proj_category,
                                       DbKgProj.proj_name.ilike('%'+query+'%')).all()
    data = [KgProj.model_validate(item) for item in result]

    projs = [d.model_dump() for d in data]
    for proj in projs:
        proj.pop("proj_conf")
    return resp_200(data={'records': projs})


@router.get("/api/proj-task/{proj_id}/{page}/{page_size}")
def search_projects(proj_id: int, page:int, page_size:int, db: Session = Depends(get_db)):
    count =  db.query(DbKgTask).filter(DbKgTask.proj_id==proj_id).count()
    total_page = ceil(count / page_size)
    start = 1
    if page <= total_page:
        start = (page-1) * page_size
   
    results = db.query(DbKgTask).filter(DbKgTask.proj_id==proj_id).order_by(DbKgTask.created).limit(page_size).offset(start).all()   
    codes = [KgTask.model_validate(node) for node in results]
    
    return resp_200(data= {"total":count,"total_page":total_page, "pages": page, "size":page_size, "records":[item.model_dump() for item in codes]})

@router.get("/api/tasks/{category}/{page}/{page_size}")
def get_all_tasks(category:str, page:int, page_size:int, db: Session = Depends(get_db)):
    count =  db.query(DbKgTask).filter(DbKgTask.task_category==category).count()
    total_page = ceil(count / page_size)
    start = 1
    if page <= total_page:
        start = (page-1) * page_size
   
    results = db.query(DbKgTask).filter(DbKgTask.task_category==category).order_by(DbKgTask.created).limit(page_size).offset(start).all()   
    codes = [KgTask.model_validate(node) for node in results]
    
    return resp_200(data= {"total":count, "pages": page, "size":page_size, "records":[item.model_dump() for item in codes]})

@router.get("/api/task-get/{task_id}")
def get_all_tasks(task_id:int,  db: Session = Depends(get_db)):
    data =  db.query(DbKgTask).filter(DbKgTask.id == task_id).first()
    tasks = []
    if data:        
        tasks.append(KgTask.model_validate(data) )    
    return resp_200(data= {"records":[item.model_dump() for item in tasks]})

@router.post("/api/task-update")
def update_task(data: KgTaskUpdate, db: Session = Depends(get_db)):
    db.query(DbKgTask).filter(DbKgTask.id == data.id).update({"task_log":data.task_log})
    db.commit()
    return resp_200(data={"error_code":0, "error_message":""})



@router.post("/api/task-create")
def proj_create_task(task:KgTaskCreate,db: Session = Depends(get_db)):
    data = DbKgTask()
    data.proj_id = task.proj_id
    data.task_category = task.task_category
    data.task_name = task.task_name
    data.task_log = ""
    data.task_content = task.task_content
    data.status = 0
    data.created = datetime.now()
    data.updated = datetime.now()
    
    db.add(data)
    db.commit()
    db.refresh(data)    
    
    return resp_200(data={'id': data.id, "error_code":0, "error_message":""})

#创建标注项目
@router.post("/api/proj-create")
def create_proj(proj:KgProjCreate,db: Session = Depends(get_db)):
    data = DbKgProj()
    data.proj_category = proj.proj_category
    data.proj_type = proj.proj_type
    data.proj_name = proj.proj_name
    data.proj_conf = proj.proj_conf
    data.status = 0
    data.created = datetime.now()
    data.updated = datetime.now()
    
    db.add(data)
    db.commit()
    db.refresh(data)    
    
    return resp_200(data={'id': data.id, "error_code":0, "error_message":""})
    
@router.get("/api/proj/{proj_id}")
def get_proj(proj_id: int, db: Session=Depends(get_db)):
    data = db.query(DbKgProj).filter(DbKgProj.id == proj_id).first()
    projs = []
    projs.append(KgProj.model_validate(data) )    
    return resp_200(data= {"records":[item.model_dump() for item in projs]})
    
@router.post("/api/proj-update")
def update_proj_conf(proj:KgProj, db: Session=Depends(get_db)):
    db.query(DbKgProj).filter(DbKgProj.id == proj.id).update({"proj_conf":proj.proj_conf, "proj_name":proj.proj_name})
    db.commit()    
    return resp_200(data= {"records":[proj.model_dump()]})

task_router = router