# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
HRSA Health Center Finder Skill

Find free and sliding-scale health centers funded by HRSA.
These Federally Qualified Health Centers (FQHCs) serve everyone
regardless of ability to pay.

Uses the findahealthcenter.hrsa.gov public endpoint.
"""

import logging

from familiar.core.api_cache import cached
from familiar.skills._api_utils import APIError, api_get

logger = logging.getLogger(__name__)

BASE_URL = "https://findahealthcenter.hrsa.gov"


# ---------------------------------------------------------------------------
# Tool handlers
# ---------------------------------------------------------------------------


def find_health_center(data: dict) -> str:
    """Find free/sliding-scale health centers (FQHCs) near a location."""
    address = data.get("address", "")
    city = data.get("city", "")
    state = data.get("state", "")
    zip_code = data.get("zip_code", "")
    radius = data.get("radius", 30)

    # Build search location
    if zip_code:
        search_loc = zip_code
    elif city and state:
        search_loc = f"{city}, {state}"
    elif address:
        search_loc = address
    else:
        return (
            "Please provide a location: ZIP code, city and state, or address. "
            "Example: zip_code='97201' or city='Portland', state='OR'"
        )

    try:
        result = _health_center_cached(search_loc, radius)
        centers = result if isinstance(result, list) else result.get("results", [])

        if not centers:
            # Provide fallback info even if API returns nothing
            return _fallback_response(search_loc)

        lines = [f"**HRSA Health Centers near {search_loc}** (sliding-scale fees):"]
        lines.append("")

        for i, center in enumerate(centers[:10], 1):
            name = center.get("name", center.get("siteName", "Health Center"))
            addr = center.get("address", center.get("siteAddress", ""))
            c_city = center.get("city", center.get("siteCity", ""))
            c_state = center.get("state", center.get("siteState", ""))
            c_zip = center.get("zip", center.get("siteZip", ""))
            phone = center.get("phone", center.get("sitePhone", ""))
            website = center.get("url", center.get("siteUrl", ""))

            location_str = ""
            if addr:
                location_str = addr
            if c_city:
                location_str += f", {c_city}"
            if c_state:
                location_str += f", {c_state}"
            if c_zip:
                location_str += f" {c_zip}"

            services = center.get("services", [])

            lines.append(f"{i}. **{name}**")
            if location_str:
                lines.append(f"   {location_str.strip(', ')}")
            if phone:
                lines.append(f"   Phone: {phone}")
            if services:
                if isinstance(services, list):
                    lines.append(f"   Services: {', '.join(services[:5])}")
            if website:
                lines.append(f"   Web: {website}")
            lines.append("")

        lines.append("_All HRSA health centers accept patients regardless of ability to pay._")
        lines.append("_Fees are based on income using a sliding scale._")
        return "\n".join(lines)

    except APIError:
        return _fallback_response(search_loc)
    except Exception as e:
        logger.error("HRSA search error: %s", e)
        return _fallback_response(search_loc)


@cached(prefix="hrsa", ttl=86400)
def _health_center_cached(location: str, radius: int) -> dict:
    try:
        return api_get(
            f"{BASE_URL}/api/search",
            params={
                "query": location,
                "radius": radius,
            },
            service_name="HRSA Health Center Finder",
            timeout=15,
        )
    except Exception:
        return {"results": []}


def _fallback_response(location: str) -> str:
    """Provide helpful info when the API is unavailable."""
    return (
        f"I couldn't reach the HRSA health center finder for {location}.\n\n"
        f"Search directly at: https://findahealthcenter.hrsa.gov/\n\n"
        "**What are HRSA Health Centers?**\n"
        "- Federally Qualified Health Centers (FQHCs)\n"
        "- Accept ALL patients regardless of ability to pay\n"
        "- Fees based on income (sliding scale)\n"
        "- Services: primary care, dental, mental health, substance abuse\n"
        "- Over 1,400 organizations with 15,000+ service sites nationwide\n\n"
        "**Other free/low-cost care options:**\n"
        "- Free clinics: https://www.nafcclinics.org/find-clinic\n"
        "- Community health: call 211 or visit https://www.211.org/"
    )


# ---------------------------------------------------------------------------
# Tool definitions
# ---------------------------------------------------------------------------

TOOLS = [
    {
        "name": "find_health_center",
        "description": (
            "Find free and sliding-scale HRSA health centers (FQHCs) near a location."
            " These federally funded centers serve everyone regardless of ability to pay."
            " No setup required."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "zip_code": {
                    "type": "string",
                    "description": "ZIP code to search near",
                },
                "city": {
                    "type": "string",
                    "description": "City name",
                },
                "state": {
                    "type": "string",
                    "description": "Two-letter state code (e.g., 'OR', 'NY')",
                },
                "address": {
                    "type": "string",
                    "description": "Full or partial street address",
                },
                "radius": {
                    "type": "integer",
                    "description": "Search radius in miles (default 30)",
                    "default": 30,
                },
            },
        },
        "handler": find_health_center,
        "category": "hrsa",
    },
]
