"""Ontology API routes."""

from __future__ import annotations

from typing import Any

from fastapi import APIRouter, HTTPException

from pycharter.wiki.api.models.ontology import (
    OntologyParseRequest,
    OntologyResponse,
    OntologyValidateRequest,
    OntologyValidateResponse,
)
from pycharter.wiki.ontology.parser import parse_ontology
from pycharter.wiki.ontology.validator import validate_ontology
from pycharter.wiki.shared.errors import OntologyError

router = APIRouter(tags=["Wiki"])


@router.post("/parse", response_model=OntologyResponse)
async def parse_ontology_endpoint(request: OntologyParseRequest):
    """Parse ontology data and return structured result."""
    try:
        artifact = parse_ontology(request.data)
        return OntologyResponse(
            version=artifact.version,
            fields={name: fo.to_dict() for name, fo in artifact.fields.items()},
        )
    except OntologyError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/validate", response_model=OntologyValidateResponse)
async def validate_ontology_endpoint(request: OntologyValidateRequest):
    """Validate ontology data and return errors."""
    errors = validate_ontology(request.data)
    return OntologyValidateResponse(valid=len(errors) == 0, errors=errors)
