from __future__ import annotations

from typing import Annotated

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

from app.api.deps import CurrentUserContext, get_current_user, get_db
from app.schemas.common import ErrorResponse
from app.schemas.ontology import OntologyParseRequest, OntologyParseResult
from app.services.ontology import SemanticOntologyService

router = APIRouter(prefix="/ontology")
DbSession = Annotated[Session, Depends(get_db)]
CurrentUser = Annotated[CurrentUserContext, Depends(get_current_user)]


@router.post(
    "/parse",
    response_model=OntologyParseResult,
    summary="解析自然语言为语义本体",
    description=(
        "把自然语言问题解析成 Day 3 约定的 8 个核心字段，并写入 AgentRun 与 SemanticParseLog。"
    ),
    responses={
        status.HTTP_400_BAD_REQUEST: {
            "model": ErrorResponse,
            "description": "请求缺少有效 query 或解析请求格式不合法。",
        }
    },
)
def parse_ontology(
    payload: OntologyParseRequest,
    db: DbSession,
    current_user: CurrentUser,
) -> OntologyParseResult:
    try:
        return SemanticOntologyService(db).parse(
            payload.model_copy(update={"user_id": current_user.username}),
            tenant_id=current_user.tenant_id,
        )
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc
