from langchain_core.tools import tool

from app.db.database import SessionLocal
from app.db.models import Department, Doctor
from app.db.queries import doctor_summary


def _fmt_doctor(d: Doctor) -> str:
    return (
        f"{d.name} ({d.specialization}, {d.department_name}) - {d.qualification}, "
        f"{d.experience_years} yrs experience, branch: {d.branch}, fee: ₹{d.consultation_fee}, "
        f"rating: {d.rating}, status: {d.status}, next available: {d.next_available}"
    )


def make_hospital_tools(tenant_id: str) -> list:
    @tool(response_format="content_and_artifact")
    def search_doctors(specialty_or_department: str = "") -> tuple[str, list[dict] | None]:
        """Search for doctors by specialty or department name (e.g. 'cardiology', 'orthopedics', 'pediatrics').
        Leave blank to list all active doctors. Returns doctor name, specialization, branch, fee and availability."""
        db = SessionLocal()
        try:
            q = db.query(Doctor).filter(Doctor.tenant_id == tenant_id)
            if specialty_or_department:
                like = f"%{specialty_or_department}%"
                q = q.filter(
                    (Doctor.specialization.ilike(like)) | (Doctor.department_name.ilike(like))
                )
            docs = q.all()
        finally:
            db.close()
        if not docs:
            return "NO_MATCH", None
        content = "\n".join(_fmt_doctor(d) for d in docs)
        return content, [doctor_summary(d) for d in docs]

    @tool
    def list_departments() -> str:
        """List all hospital departments with a short description and doctor count."""
        db = SessionLocal()
        try:
            deps = db.query(Department).filter(Department.tenant_id == tenant_id).all()
        finally:
            db.close()
        if not deps:
            return "NO_MATCH"
        return "\n".join(f"{d.name}: {d.description}" for d in deps)

    @tool
    def check_availability(doctor_name: str) -> str:
        """Check a specific doctor's next available appointment slot and active status. Pass the doctor's name."""
        db = SessionLocal()
        try:
            like = f"%{doctor_name}%"
            doc = db.query(Doctor).filter(Doctor.tenant_id == tenant_id, Doctor.name.ilike(like)).first()
        finally:
            db.close()
        if not doc:
            return "NO_MATCH"
        if doc.status != "active":
            return f"{doc.name} is currently unavailable. Next available: {doc.next_available}."
        return f"{doc.name} is active. Next available slot: {doc.next_available} at {doc.branch}."

    return [search_doctors, list_departments, check_availability]
