# 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

"""
Connected Service Search Skill

Agent-facing tool for searching across all connected services (Drive,
Email, Nextcloud, Gitea, Jellyfin, Video library, GitHub).  Wraps the
existing ``search_service()`` dispatcher from ``_browse.py`` so the
agent can reason about queries and present intelligent results.
"""

import json
import logging

logger = logging.getLogger(__name__)


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _build_text_and_json(items, summary, service, query):
    """Build the dual-format return string: human text + JSON marker."""
    lines = [f"Found {len(items)} results in {service} for: {query}\n"]
    for i, item in enumerate(items, 1):
        lines.append(f"  {i}. {item.get('name', '(untitled)')}")
        detail = item.get("detail", "")
        if detail:
            lines.append(f"     {detail}")
        url = item.get("url", "")
        if url:
            lines.append(f"     {url}")
        lines.append("")

    payload = {"items": items, "summary": summary}
    lines.append("SEARCH_RESULTS_JSON:")
    lines.append(json.dumps(payload))
    return "\n".join(lines)


# ---------------------------------------------------------------------------
# Tool handler
# ---------------------------------------------------------------------------

# Services accepted by the dispatcher
_VALID_SERVICES = ("drive", "email", "nextcloud", "gitea", "jellyfin", "video", "github")


def service_search(data: dict) -> str:
    """Search a connected service by name and query."""
    from familiar.channels.connect_wizard._browse import search_service

    service = data.get("service", "").strip().lower()
    query = data.get("query", "").strip()

    if not service:
        return "Please specify a service to search (drive, email, nextcloud, gitea, jellyfin, video, github)."
    if service not in _VALID_SERVICES:
        return f"Unknown service: {service}. Available services: {', '.join(_VALID_SERVICES)}"
    if not query:
        return "Please provide a search query."

    result = search_service(service, query)
    items = result.get("items", [])
    summary = result.get("summary", f"{len(items)} results")

    if result.get("error"):
        return f"Search failed for {service}: {result['error']}"

    if not items:
        return f"No results found in {service} for: {query}"

    return _build_text_and_json(items, summary, service, query)


# ---------------------------------------------------------------------------
# Tool definitions (auto-discovered by skill loader)
# ---------------------------------------------------------------------------

TOOLS = [
    {
        "name": "service_search",
        "description": (
            "Search a connected service (Google Drive, Email, Nextcloud, Gitea, "
            "Jellyfin, local video library, or GitHub). Use this when the user "
            "wants to find files, emails, repos, media, or other items in their "
            "connected services."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "service": {
                    "type": "string",
                    "enum": list(_VALID_SERVICES),
                    "description": (
                        "Which service to search: drive, email, nextcloud, "
                        "gitea, jellyfin, video, or github"
                    ),
                },
                "query": {
                    "type": "string",
                    "description": "The search query",
                },
            },
            "required": ["service", "query"],
        },
        "handler": service_search,
        "category": "services",
    },
]
