from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.dependencies import get_current_admin
from app.core.responses import api_success
from app.models.admin import Admin
from app.models.knowledge import Knowledge
from app.schemas.admin import KnowledgeSaveRequest
from app.services.admin_service import OperationLogService

router = APIRouter()


@router.get("/knowledge/list")
def list_knowledge(db: Session = Depends(get_db), current_admin: Admin = Depends(get_current_admin)) -> dict:
    items = db.scalars(select(Knowledge).order_by(Knowledge.id.desc())).all()
    return api_success([_knowledge_dict(item) for item in items])


@router.post("/knowledge")
def create_knowledge(
    payload: KnowledgeSaveRequest,
    db: Session = Depends(get_db),
    current_admin: Admin = Depends(get_current_admin),
) -> dict:
    knowledge = Knowledge(
        name=payload.name,
        feishu_space_id=payload.feishuSpaceId,
        feishu_node_id=payload.feishuNodeId,
        status=payload.status,
        remark=payload.remark,
    )
    db.add(knowledge)
    db.flush()
    OperationLogService.write(db, admin_id=current_admin.id, module="knowledge", action="create", target_id=knowledge.id)
    db.commit()
    db.refresh(knowledge)
    return api_success(_knowledge_dict(knowledge))


@router.put("/knowledge/{knowledge_id}")
def update_knowledge(
    knowledge_id: int,
    payload: KnowledgeSaveRequest,
    db: Session = Depends(get_db),
    current_admin: Admin = Depends(get_current_admin),
) -> dict:
    knowledge = _get_knowledge(db, knowledge_id)
    knowledge.name = payload.name
    knowledge.feishu_space_id = payload.feishuSpaceId
    knowledge.feishu_node_id = payload.feishuNodeId
    knowledge.status = payload.status
    knowledge.remark = payload.remark
    db.add(knowledge)
    OperationLogService.write(db, admin_id=current_admin.id, module="knowledge", action="update", target_id=knowledge.id)
    db.commit()
    db.refresh(knowledge)
    return api_success(_knowledge_dict(knowledge))


@router.delete("/knowledge/{knowledge_id}")
def delete_knowledge(
    knowledge_id: int,
    db: Session = Depends(get_db),
    current_admin: Admin = Depends(get_current_admin),
) -> dict:
    knowledge = _get_knowledge(db, knowledge_id)
    db.delete(knowledge)
    OperationLogService.write(db, admin_id=current_admin.id, module="knowledge", action="delete", target_id=knowledge.id)
    db.commit()
    return api_success()


def _get_knowledge(db: Session, knowledge_id: int) -> Knowledge:
    knowledge = db.get(Knowledge, knowledge_id)
    if knowledge is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="知识库不存在")
    return knowledge


def _knowledge_dict(knowledge: Knowledge) -> dict:
    return {
        "id": knowledge.id,
        "name": knowledge.name,
        "feishuSpaceId": knowledge.feishu_space_id,
        "feishuNodeId": knowledge.feishu_node_id,
        "status": knowledge.status,
        "remark": knowledge.remark,
        "createdAt": knowledge.created_at,
        "updatedAt": knowledge.updated_at,
    }
