"""Lineage API routes."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException

from pycharter.wiki.api.dependencies import get_db_session
from pycharter.wiki.api.models.lineage import FieldLineageRequest, LineagePathRequest
from pycharter.wiki.knowledge.lineage import LineageTracker
from pycharter.wiki.shared.errors import GraphError

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


@router.post("/upstream")
async def get_upstream(
    request: FieldLineageRequest,
    relationship_types: str | None = None,
    session=Depends(get_db_session),
):
    """Get upstream fields. Optional comma-separated relationship_types filter."""
    try:
        tracker = LineageTracker(session)
        types = relationship_types.split(",") if relationship_types else None
        return tracker.get_upstream(request.field_id, relationship_types=types)
    except GraphError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/downstream")
async def get_downstream(
    request: FieldLineageRequest,
    relationship_types: str | None = None,
    session=Depends(get_db_session),
):
    """Get downstream fields. Optional comma-separated relationship_types filter."""
    try:
        tracker = LineageTracker(session)
        types = relationship_types.split(",") if relationship_types else None
        return tracker.get_downstream(request.field_id, relationship_types=types)
    except GraphError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/path")
async def get_lineage_path(
    request: LineagePathRequest, session=Depends(get_db_session)
):
    """Get the lineage path between two fields."""
    try:
        tracker = LineageTracker(session)
        return tracker.get_lineage_path(
            request.source_field_id, request.target_field_id
        )
    except GraphError as e:
        raise HTTPException(status_code=400, detail=str(e))
