"""
API Router — JSON endpoints
"""
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from typing import Optional
from pydantic import BaseModel

from ..schemas.schemas import AIAnalysisRequest, AIAnalysisResponse
from ..services.database import get_db
from ..services.auth_service import get_current_user
from ..services.ai_service import analyze_case, get_chatbot_response, VALID_CATEGORIES
from ..services.lawyer_service import recommend_lawyers

router = APIRouter()


class ChatRequest(BaseModel):
    message: str
    case_context: Optional[str] = None
    # Note: no language field needed — the AI auto-detects English/Urdu/Roman Urdu from the message itself


class ChatResponse(BaseModel):
    response: str


@router.post("/analyze", response_model=AIAnalysisResponse)
async def analyze_case_api(req: AIAnalysisRequest, user=Depends(get_current_user), db: Session = Depends(get_db)):
    return AIAnalysisResponse(**analyze_case(req.description))


@router.post("/chat", response_model=ChatResponse)
async def chat(req: ChatRequest):
    return ChatResponse(response=get_chatbot_response(req.message, req.case_context))


@router.get("/recommend-lawyers")
async def get_recommendations(
    category: str, city: Optional[str] = None, top_n: int = 5,
    user=Depends(get_current_user), db: Session = Depends(get_db),
):
    results = recommend_lawyers(db, category, city, top_n)
    return [
        {
            "id": r["lawyer"].id, "name": r["lawyer"].name,
            "specialization": r["lawyer"].specialization, "city": r["lawyer"].city,
            "rating": r["lawyer"].rating, "experience_years": r["lawyer"].experience_years,
            "consultation_fee_pkr": r["lawyer"].consultation_fee_pkr,
            "success_rate_percentage": r["lawyer"].success_rate_percentage,
            "law_firm_name": r["lawyer"].law_firm_name,
            "contact_email": r["lawyer"].contact_email,
            "match_score": r["match_score"], "reason": r["reason"],
        }
        for r in results
    ]


@router.get("/categories")
async def get_categories():
    return {"categories": VALID_CATEGORIES}
