

from fastapi import APIRouter
from pro_craft import Intel,AsyncIntel
from pro_craft.utils import create_async_session
from .models import *

def create_router(database_url: str,
                  slave_database_url: str,
                  model_name: str,
                  logger = None):
    """
    # TODO 整理改为异步
    创建一个包含 ProCraft 路由的 FastAPI APIRouter 实例。

    Args:
        database_url (str): 数据库连接字符串。
        model_name (str): 用于 Intel 实例的模型名称。
        api_key_secret (str, optional): 用于验证 API Key 的秘密字符串。
                                        如果提供，它将覆盖环境变量 PRO_CRAFT_API_KEY。
                                        如果都不提供，会使用硬编码的 'your_default_secret_key'。
    Returns:
        APIRouter: 配置好的 FastAPI APIRouter 实例。
    """

    intels = AsyncIntel(
        database_url=database_url,
        model_name=model_name,
        logger=logger
        )

    router = APIRouter(
        tags=["prompt"] # 这里使用 Depends 确保每次请求都验证
    )

    # 自动修改
    @router.post("/push_order",
                description="可选 train,inference,summary,finetune,patch",
                response_model=PromptResponse,
                )
    async def push_order(request: PushOrderRequest):
        result = await intels.push_action_order(
            demand=request.demand,
            prompt_id=request.prompt_id,
            action_type=request.action_type
        )
        return PromptResponse(msg = "success",content=result)

    # 人为干预

    @router.get("/registered_prompt",
                description="获取以注册的提示词",
                response_model=PromptResponse)
    async def get_prompt():
        result = ["memorycard-format",
        "memorycard-polish",
        "memorycard-merge",
        "memorycard-score",
        "memorycard-generate-content",
        "user-overview",
        "user-relationship-extraction",
        "avatar-brief",
        "avatar-personality-extraction",
        "avatar-desensitization",
        "biograph-free-writer",
        "biograph-paid-title",
        "biograph-outline",
        "biograph-brief",
        "biograph-extract-person-name",
        "biograph-extract-place",
        "biograph-extract-material",
        "biograph-writer"]
        
        return PromptResponse(msg = "success",content=result)

    @router.post("/get_prompt",
                description="获得现行提示词",
                response_model=PromptResponse)
    async def get_prompt(request: GetPromptRequest):
        async with create_async_session(intels.engine) as session:
            result = await intels.get_prompt_safe(
                prompt_id=request.prompt_id,
                session=session
            )
        return PromptResponse(msg = "success",content=result)
    
    @router.post("/update_prompt",
                description="更新现行提示词",
                response_model=PromptResponse)
    async def update_prompt(request: UpdatePromptRequest):
        async with create_async_session(intels.engine) as session:
            await intels.save_prompt(
                            prompt_id = request.prompt_id,
                            new_prompt = request.prompt,
                            use_case = "",
                            action_type = "inference",
                            demand = "上传",
                            score = 70,
                            session = session)
        return PromptResponse(msg = "success",content=None)

    @router.post("/rollback_prompt",
                description="回滚现行提示词",
                response_model=PromptResponse)
    async def roll_back(request: RollBackPromptRequest):
        async with create_async_session(intels.engine) as session:
            result = await intels.get_prompt_safe(
                prompt_id=request.prompt_id,
                version = request.version,
                session=session
            )
            assert result.version == request.version
            await intels.save_prompt(
                            prompt_id = request.prompt_id,
                            new_prompt = result.prompt,
                            use_case = result.use_case,
                            action_type = "inference",
                            demand = "",
                            score = 61,
                            session = session)
        return PromptResponse(msg = "success",content=None)

    #系统级别服务
    
    @router.post("/sync_database")
    async def sync_database(request: SyncDataBaseRequest):
        slave_database_url = request.slave_database_url or slave_database_url
        result = await intels.sync_production_database(slave_database_url)
        return PromptResponse(msg = "success",content=result)

    return router

