"""Ingestion API routes."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query

from pycharter.wiki.api.dependencies import get_db_session
from pycharter.wiki.ingestion.importer import OntologyImporter
from pycharter.wiki.shared.errors import IngestionError

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


@router.post("/import")
async def import_ontology(
    contract_dir: str = Query(..., description="Path to contract directory"),
    contract_id: str | None = Query(None),
    author: str = Query("api-importer"),
    session=Depends(get_db_session),
):
    """Import ontology from a contract directory."""
    try:
        importer = OntologyImporter(session)
        result = importer.import_from_contract_dir(
            contract_dir, contract_id=contract_id, author=author
        )
        return result
    except IngestionError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/import-all")
async def import_all_ontologies(
    base_dir: str = Query(..., description="Base directory with contract subdirs"),
    author: str = Query("api-importer"),
    session=Depends(get_db_session),
):
    """Import ontologies from all contract subdirectories."""
    try:
        importer = OntologyImporter(session)
        results = importer.import_from_directory(base_dir, author=author)
        return results
    except IngestionError as e:
        raise HTTPException(status_code=400, detail=str(e))
