from typing import Optional
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.models.user import User
from app.schemas.common import ResponseModel
from app.services import lineage_service
from app.api.deps import get_current_user

router = APIRouter()


@router.post("/parse")
def parse_lineage(
    sql: str,
    target_table: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    records = lineage_service.parse_sql_lineage(db, sql, target_table)
    return ResponseModel(data={"records_created": len(records)})


@router.get("/graph")
def get_graph(
    table_name: Optional[str] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    graph = lineage_service.get_lineage_graph(db, table_name=table_name)
    return ResponseModel(data=graph)
