"""Concept relationship CRUD API routes."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, Field

from pycharter.wiki.api.dependencies import get_db_session
from pycharter.wiki.knowledge.graph import KnowledgeGraph
from pycharter.wiki.shared.errors import GraphError

router = APIRouter(tags=["Wiki - Concept Graph"])


class CreateConceptRelationshipRequest(BaseModel):
    """Request body for creating a concept relationship."""

    source_concept_id: str = Field(..., description="UUID of source concept")
    target_concept_id: str = Field(..., description="UUID of target concept")
    relationship_type: str = Field(..., description="Relationship type name")


@router.get("/concepts/{concept_id}/relationships")
async def get_concept_relationships(
    concept_id: str,
    type: str | None = None,
    direction: str = "both",
    session=Depends(get_db_session),
):
    """Get concept-level relationships, optionally filtered by type and direction."""
    if direction not in ("outgoing", "incoming", "both"):
        raise HTTPException(
            status_code=400,
            detail="direction must be 'outgoing', 'incoming', or 'both'",
        )
    try:
        kg = KnowledgeGraph(session)
        return kg.get_concept_relationships(
            concept_id,
            relationship_type=type,
            direction=direction,
        )
    except GraphError as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/concepts/relationships", status_code=201)
async def create_concept_relationship(
    request: CreateConceptRelationshipRequest,
    session=Depends(get_db_session),
):
    """Create a typed edge between two concepts."""
    from pycharter.db.models.wiki.concept_relationship import ConceptRelationshipModel

    cr = ConceptRelationshipModel(
        source_concept_id=request.source_concept_id,
        target_concept_id=request.target_concept_id,
        relationship_type=request.relationship_type,
    )
    session.add(cr)
    session.flush()
    return {"id": str(cr.id), "status": "created"}


@router.delete("/concepts/relationships/{relationship_id}")
async def delete_concept_relationship(
    relationship_id: str,
    session=Depends(get_db_session),
):
    """Delete a concept relationship edge."""
    from pycharter.db.models.wiki.concept_relationship import ConceptRelationshipModel

    row = (
        session.query(ConceptRelationshipModel)
        .filter(ConceptRelationshipModel.id == relationship_id)
        .first()
    )
    if row is None:
        raise HTTPException(status_code=404, detail="Relationship not found")
    session.delete(row)
    session.flush()
    return {"status": "deleted"}
