import json
import logging
from typing import Any
from urllib.parse import urlencode

import pandas as pd
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client

from config import MCP_BASE_URL, MCP_API_KEY

logger = logging.getLogger(__name__)

# Build MCP URL with API key
params = {"api_key": MCP_API_KEY}
MCP_URL = f"{MCP_BASE_URL}?{urlencode(params)}"


async def lookup_property(address: str) -> pd.DataFrame:
    """
    Look up properties by address using MCP tool.
    """
    try:
        async with streamablehttp_client(MCP_URL) as (read, write, _):
            async with ClientSession(read, write) as session:
                await session.initialize()
                logger.info("Calling MCP tool with address: %s", address)
                
                result = await session.call_tool(
                    "scrape_properties",
                    {
                        "location": address,
                        "listing_type": "FOR_SALE",
                        "property_type": ["single_family"],
                        "limit": 5
                    }
                )
                
                if not result.content:
                    logger.error("No content returned from MCP tool.")
                    return pd.DataFrame()
                
                # Extract data from result
                if hasattr(result.content[0], "text") and result.content[0].text:
                    data = json.loads(result.content[0].text)
                else:
                    data = result.content[0]
                
                if not data:
                    return pd.DataFrame()
                
                filtered = []
                for prop in data:
                    desc = prop.get("description", {})
                    location = prop.get("location", {}).get("address", {})
                    filtered.append({
                        "street": location.get("line"),
                        "city": location.get("city"),
                        "state": location.get("state_code"),
                        "zip_code": location.get("postal_code"),
                        "beds": desc.get("beds"),
                        "baths": desc.get("baths_full"),
                        "sqft": desc.get("sqft"),
                        "list_price": prop.get("list_price"),
                        "sold_price": prop.get("sold_price"),
                        "property_url": prop.get("href"),
                    })
                
                return pd.DataFrame(filtered)
    
    except Exception as e:
        logger.exception("MCP lookup failed for address: %s", address)
        raise
