# 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

"""
GlobalGiving Project Search Skill

Search and explore GlobalGiving projects and NGOs worldwide.

Setup:
    GLOBALGIVING_API_KEY=your_api_key

Get a key at: https://www.globalgiving.org/api/
API: https://api.globalgiving.org/api/public/projectservice/
"""

import logging

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

logger = logging.getLogger(__name__)

BASE_URL = "https://api.globalgiving.org/api/public/projectservice"


def _api_key() -> str:
    return get_env("GLOBALGIVING_API_KEY") or ""


def _check_config() -> str:
    if not _api_key():
        return (
            "GlobalGiving API key not configured.\n"
            "Set GLOBALGIVING_API_KEY in your environment.\n"
            "Get a key at: https://www.globalgiving.org/api/"
        )
    return ""


def _params() -> dict:
    return {"api_key": _api_key()}


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


def search_projects(data: dict) -> str:
    """Search GlobalGiving projects."""
    err = _check_config()
    if err:
        return err

    keyword = data.get("keyword", "").strip()
    theme = data.get("theme", "").strip()
    country = data.get("country", "").strip()

    if not keyword and not theme and not country:
        return "Please provide a keyword, theme, or country to search."

    try:
        params = _params()
        if keyword:
            params["q"] = keyword

        # Build URL based on filters
        if theme:
            url = f"{BASE_URL}/themes/{theme}/projects/active"
        elif country:
            url = f"{BASE_URL}/countries/{country}/projects/active"
        else:
            url = f"{BASE_URL}/all/projects/active"

        result = _search_cached(url, keyword, theme, country)

        projects_data = result.get("projects", result.get("project", {}))
        projects = projects_data.get("project", [])
        if isinstance(projects, dict):
            projects = [projects]

        if not projects:
            return "No GlobalGiving projects found."

        lines = [f"**GlobalGiving Projects** (showing {len(projects[:15])}):", ""]

        for i, p in enumerate(projects[:15], 1):
            title = p.get("title", "Untitled")
            project_id = p.get("id", "")
            org_name = p.get("organization", {}).get("name", "")
            country_name = p.get("country", "")
            funding = p.get("funding", 0)
            goal = p.get("goal", 0)
            theme_name = p.get("themeName", "")

            lines.append(f"{i}. **{title}**")
            details = []
            if project_id:
                details.append(f"ID: {project_id}")
            if org_name:
                details.append(org_name)
            if country_name:
                details.append(country_name)
            if theme_name:
                details.append(theme_name)
            lines.append(f"   {' | '.join(details)}")

            if goal:
                pct = (funding / goal * 100) if goal else 0
                lines.append(f"   Funded: ${funding:,.0f} / ${goal:,.0f} ({pct:.0f}%)")
            lines.append("")

        return "\n".join(lines)

    except APIError as e:
        return str(e)
    except Exception as e:
        logger.error("GlobalGiving search error: %s", e)
        return f"Error searching projects: {e}"


@cached(prefix="globalgiving_search", ttl=1800)
def _search_cached(url: str, keyword: str, theme: str, country: str) -> dict:
    params = _params()
    if keyword:
        params["q"] = keyword
    return api_get(url, params=params, service_name="GlobalGiving")


def project_details(data: dict) -> str:
    """Get details about a specific GlobalGiving project."""
    err = _check_config()
    if err:
        return err

    project_id = data.get("project_id", "").strip()
    if not project_id:
        return "Please provide a project_id."

    try:
        result = _project_cached(project_id)

        project = result.get("project", result)

        title = project.get("title", "")
        org = project.get("organization", {})
        org_name = org.get("name", "")
        country = project.get("country", "")
        summary = project.get("summary", project.get("projectSummary", ""))
        funding = project.get("funding", 0)
        goal = project.get("goal", 0)
        donors = project.get("numberOfDonations", 0)
        status = project.get("status", "")
        theme = project.get("themeName", "")
        url = project.get("projectLink", "")

        lines = [
            f"**{title}**",
            "",
        ]
        if org_name:
            lines.append(f"  Organization: {org_name}")
        if country:
            lines.append(f"  Country: {country}")
        if theme:
            lines.append(f"  Theme: {theme}")
        if status:
            lines.append(f"  Status: {status}")
        if goal:
            pct = (funding / goal * 100) if goal else 0
            lines.append(f"  Funding: ${funding:,.0f} / ${goal:,.0f} ({pct:.0f}%)")
        if donors:
            lines.append(f"  Donors: {donors}")
        if url:
            lines.append(f"  URL: {url}")
        if summary:
            lines.append(f"\n  {summary[:500]}")

        return "\n".join(lines)

    except APIError as e:
        return str(e)
    except Exception as e:
        logger.error("GlobalGiving details error: %s", e)
        return f"Error fetching project details: {e}"


@cached(prefix="globalgiving_project", ttl=3600)
def _project_cached(project_id: str) -> dict:
    return api_get(
        f"{BASE_URL}/projects/{project_id}",
        params=_params(),
        service_name="GlobalGiving",
    )


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

TOOLS = [
    {
        "name": "search_projects",
        "description": (
            "Search GlobalGiving for international development projects."
            " Filter by keyword, theme, or country."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "keyword": {
                    "type": "string",
                    "description": "Search keyword",
                },
                "theme": {
                    "type": "string",
                    "description": "Theme: education, health, climate, hunger, etc.",
                },
                "country": {
                    "type": "string",
                    "description": "Country code (e.g., 'US', 'KE', 'IN')",
                },
            },
        },
        "handler": search_projects,
        "category": "globalgiving",
    },
    {
        "name": "project_details",
        "description": (
            "Get details about a specific GlobalGiving project."
            " Shows organization, funding progress, donors, and description."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "project_id": {
                    "type": "string",
                    "description": "GlobalGiving project ID",
                },
            },
            "required": ["project_id"],
        },
        "handler": project_details,
        "category": "globalgiving",
    },
]
