import logging
from typing import Any, Dict, Tuple
from urllib.parse import quote

import httpx

from config import ATTOM_BASE_URL, ATTOM_API_KEY
from utils import parse_attom_salescomps_v2, normalize_street_no_trailing_comma

logger = logging.getLogger(__name__)


def fetch_attom_comps(
    address: str,
    city: str,
    state: str,
    zip_code: str,
    miles: int = 3,
    sale_months: int = 24,
    api_key: str = ATTOM_API_KEY
) -> Tuple[Dict[str, Any], list]:
    """
    Fetch comparable properties from ATTOM API.  """
    street_normalized = normalize_street_no_trailing_comma(address.strip())
    street_for_url = quote(street_normalized, safe="")
    city_for_url = quote(city or "", safe="")
    state_for_url = quote(state or "", safe="")
    zip_for_url = quote(str(zip_code or ""), safe="")
    
    attom_url = f"{ATTOM_BASE_URL}/{street_for_url}/{city_for_url}/US/{state_for_url}/{zip_for_url}"
    
    logger.info("ATTOM v2 URL: %s (miles=%d, months=%d)", attom_url, miles, sale_months)
    
    headers = {"accept": "application/json", "apikey": api_key}
    params = {
        "searchType": "Radius",
        "minComps": 1,
        "maxComps": 12,
        "miles": miles,
        "saleDateRange": sale_months,
    }
    
    with httpx.Client(timeout=30) as client:
        response = client.get(attom_url, headers=headers, params=params)
        response.raise_for_status()
        payload = response.json()
    
    return parse_attom_salescomps_v2(payload)


def get_attom_estimate(
    subject_address: str,
    subject_city: str,
    subject_state: str,
    subject_zip: str,
    subject_sqft: int = None,
    api_key: str = ATTOM_API_KEY
) -> Dict[str, Any]:
    """
    Get property estimate using ATTOM comparables with adaptive search radius.
    """
    if not api_key:
        return {"error": "ATTOM API key not configured"}
    
    attempts = [(3, 24), (5, 24), (8, 36)]
    comps = []
    subject = None
    
    for miles, months in attempts:
        try:
            subject, comps = fetch_attom_comps(
                subject_address,
                subject_city,
                subject_state,
                subject_zip,
                miles=miles,
                sale_months=months,
                api_key=api_key
            )
            logger.info(
                "ATTOM attempt miles=%s months=%s -> comps=%d",
                miles, months, len(comps)
            )
            if comps:
                break
        except httpx.HTTPStatusError as he:
            logger.warning(
                "ATTOM HTTP error on attempt miles=%s months=%s: %s",
                miles, months, he
            )
        except Exception:
            logger.exception(
                "ATTOM parse/fetch failed for miles=%s months=%s",
                miles, months
            )
    
    logger.info("ATTOM parsed subject sqft=%s", subject.get("sqft") if subject else None)
    logger.info("ATTOM parsed comps count=%d", len(comps))
    
    return {
        "subject": subject,
        "comps": comps,
        "attempts": attempts,
    }
