from langchain_core.tools import tool

from app.db.database import SessionLocal
from app.db.models import Agent, Property
from app.db.queries import property_summary


def _fmt_property(p: Property) -> str:
    bhk = f"{p.bhk}BHK " if p.bhk else ""
    return (
        f"{p.title} - {bhk}{p.type} in {p.locality}, {p.city} | ₹{p.price:,} | {p.area_sqft} sqft | "
        f"status: {p.status} | amenities: {p.amenities} | id: {p.id}"
    )


def make_realestate_tools(tenant_id: str) -> list:
    @tool(response_format="content_and_artifact")
    def search_properties(
        city: str = "",
        locality: str = "",
        property_type: str = "",
        min_bhk: int = 0,
        max_price: int = 0,
    ) -> tuple[str, list[dict] | None]:
        """Search available properties by city, locality/area name, type (apartment/villa/plot/commercial),
        minimum BHK, and/or maximum price in INR. Leave a field as "" or 0 to not filter on it.
        city and locality are matched leniently against both fields, so either can hold an area name
        like "Andheri" or a city name like "Mumbai"."""
        db = SessionLocal()
        try:
            q = db.query(Property).filter(Property.tenant_id == tenant_id, Property.status == "available")
            if city:
                like = f"%{city}%"
                q = q.filter((Property.city.ilike(like)) | (Property.locality.ilike(like)))
            if locality:
                like = f"%{locality}%"
                q = q.filter((Property.city.ilike(like)) | (Property.locality.ilike(like)))
            if property_type:
                q = q.filter(Property.type.ilike(f"%{property_type}%"))
            if min_bhk > 0:
                q = q.filter(Property.bhk >= min_bhk)
            if max_price > 0:
                q = q.filter(Property.price <= max_price)
            props = q.all()
        finally:
            db.close()
        if not props:
            return "NO_MATCH", None
        content = "\n".join(_fmt_property(p) for p in props)
        return content, [property_summary(p) for p in props]

    @tool
    def get_property_details(property_title_or_id: str) -> str:
        """Get full details (description, amenities, price, area, agent) for a specific property by its title or id."""
        db = SessionLocal()
        try:
            like = f"%{property_title_or_id}%"
            p = db.query(Property).filter(
                Property.tenant_id == tenant_id,
                (Property.title.ilike(like)) | (Property.id == property_title_or_id),
            ).first()
        finally:
            db.close()
        if not p:
            return "NO_MATCH"
        return (
            f"{p.title}: {p.description} Price: ₹{p.price:,}, Area: {p.area_sqft} sqft, "
            f"Amenities: {p.amenities}, Status: {p.status}."
        )

    @tool
    def get_agent_contact(property_title_or_id: str) -> str:
        """Get the assigned agent's name, phone and email for a specific property by its title or id."""
        db = SessionLocal()
        try:
            like = f"%{property_title_or_id}%"
            p = db.query(Property).filter(
                Property.tenant_id == tenant_id,
                (Property.title.ilike(like)) | (Property.id == property_title_or_id),
            ).first()
            if not p:
                return "NO_MATCH"
            agent = db.query(Agent).filter(Agent.id == p.agent_id).first()
        finally:
            db.close()
        if not agent:
            return "NO_MATCH"
        return f"Agent for {p.title}: {agent.name}, phone: {agent.phone}, email: {agent.email}."

    return [search_properties, get_property_details, get_agent_contact]
