# 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

"""
SAMHSA Treatment Locator Skill

Find substance abuse and mental health treatment facilities.
Uses the SAMHSA Behavioral Health Treatment Services Locator.

The public locator at findtreatment.gov requires geocoded coordinates.
This skill uses the public-facing locator endpoint which accepts
address/city/state/zip searches.

API: https://findtreatment.gov/
"""

import logging
import re

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

logger = logging.getLogger(__name__)

# The public locator uses a search-by-location endpoint
BASE_URL = "https://findtreatment.gov"


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


def find_treatment(data: dict) -> str:
    """Find substance abuse and mental health treatment facilities."""
    city = data.get("city", "")
    state = data.get("state", "")
    zip_code = data.get("zip_code", "")
    service_type = data.get("service_type", "").upper()

    if not (city or state or zip_code):
        return (
            "Please provide a location: city and state, or ZIP code. "
            "Example: city='Portland', state='OR' or zip_code='97201'"
        )

    # Build location string
    location_parts = []
    if city:
        location_parts.append(city)
    if state:
        location_parts.append(state)
    if zip_code:
        location_parts.append(zip_code)
    location = ", ".join(location_parts)

    try:
        result = _find_treatment_cached(city, state, zip_code, service_type)
        rows = result.get("rows", [])

        if not rows:
            return f"No treatment facilities found near {location}."

        # Build response
        lines = [f"**Treatment facilities near {location}:**"]
        lines.append("")

        for i, facility in enumerate(rows[:15], 1):
            name = facility.get("name1", facility.get("name2", "Unknown Facility"))
            addr_parts = []
            street = facility.get("street1", "")
            if street:
                addr_parts.append(street)
            f_city = facility.get("city", "")
            f_state = facility.get("state", "")
            f_zip = facility.get("zip", "")
            if f_city or f_state:
                addr_parts.append(f"{f_city}, {f_state} {f_zip}".strip())
            address = " — ".join(addr_parts)

            phone = facility.get("phone", "")
            website = facility.get("website", "")

            # Services
            services = []
            if facility.get("sa", False):
                services.append("Substance Abuse")
            if facility.get("mh", False):
                services.append("Mental Health")
            if facility.get("dt", False):
                services.append("Detox")

            service_str = ", ".join(services) if services else ""

            lines.append(f"{i}. **{name}**")
            if address:
                lines.append(f"   {address}")
            if phone:
                # Clean phone
                clean_phone = re.sub(r"[^\d\-()]", "", str(phone))
                lines.append(f"   Phone: {clean_phone}")
            if service_str:
                lines.append(f"   Services: {service_str}")
            if website:
                lines.append(f"   Web: {website}")
            lines.append("")

        total = result.get("totalResults", len(rows))
        if total > 15:
            lines.append(f"_Showing 15 of {total} facilities._")

        lines.append("")
        lines.append("**24/7 SAMHSA Helpline: 1-800-662-4357** (free, confidential)")

        return "\n".join(lines)

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


@cached(prefix="samhsa", ttl=86400)
def _find_treatment_cached(city: str, state: str, zip_code: str, service_type: str) -> dict:
    params = {}
    if city:
        params["scity"] = city
    if state:
        params["sstate"] = state
    if zip_code:
        params["szip"] = zip_code
    if service_type:
        params["sCodes"] = service_type

    return api_get(
        f"{BASE_URL}/locator/ExportResults/v2",
        params=params,
        service_name="SAMHSA Treatment Locator",
        timeout=15,
    )


def _fallback_response(location: str) -> str:
    """Provide useful info even when the API is unavailable."""
    return (
        f"I couldn't reach the SAMHSA treatment locator for {location}.\n\n"
        "You can search directly at: https://findtreatment.gov/\n\n"
        "**Immediate help:**\n"
        "- **SAMHSA Helpline**: 1-800-662-4357 (24/7, free, confidential)\n"
        "- **988 Suicide & Crisis Lifeline**: Call or text 988\n"
        "- **Crisis Text Line**: Text HOME to 741741\n"
        "- **NAMI Helpline**: 1-800-950-6264"
    )


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

TOOLS = [
    {
        "name": "find_treatment",
        "description": (
            "Find substance abuse and mental health treatment facilities near a location."
            " Uses the SAMHSA Behavioral Health Treatment Services Locator."
            " No setup required. Always includes the SAMHSA helpline number."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "City name",
                },
                "state": {
                    "type": "string",
                    "description": "Two-letter state code (e.g., 'OR', 'NY')",
                },
                "zip_code": {
                    "type": "string",
                    "description": "ZIP code",
                },
                "service_type": {
                    "type": "string",
                    "description": (
                        "Filter: SA (substance abuse), MH (mental health),"
                        " DT (detox), OTP (opioid treatment). Leave empty for all."
                    ),
                    "default": "",
                },
            },
        },
        "handler": find_treatment,
        "category": "samhsa",
    },
]
