# 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

"""Setup skill — check and manage service connections from conversation."""

from __future__ import annotations

import logging

logger = logging.getLogger(__name__)


def check_setup_status(data: dict) -> str:
    """Return which services are configured, tested, and recommended."""
    from familiar.channels.connect_wizard.auto_setup import AutoSetupEngine
    from familiar.channels.connect_wizard.service_catalog import (
        SERVICE_CATALOG,
        get_services_for_job_class,
    )

    engine = AutoSetupEngine()
    status = engine.get_setup_status()

    configured = []
    not_configured = []
    for key, info in status.items():
        entry = SERVICE_CATALOG.get(key)
        if not entry or not entry.env_vars:
            continue
        name = entry.display_name
        if info["configured"]:
            configured.append(name)
        else:
            not_configured.append(name)

    # Recommended but missing
    job_class = data.get("job_class", "")
    missing_recommended: list[str] = []
    if job_class:
        recommended = get_services_for_job_class(job_class)
        for svc in recommended:
            s = status.get(svc.key, {})
            if not s.get("configured"):
                missing_recommended.append(svc.display_name)

    lines = []
    lines.append(f"Configured ({len(configured)}):")
    for name in sorted(configured):
        lines.append(f"  - {name}")

    if missing_recommended:
        lines.append(f"\nRecommended but missing ({len(missing_recommended)}):")
        for name in missing_recommended:
            lines.append(f"  - {name}")

    lines.append(f"\nNot configured ({len(not_configured)}):")
    for name in sorted(not_configured)[:10]:
        lines.append(f"  - {name}")
    if len(not_configured) > 10:
        lines.append(f"  ... and {len(not_configured) - 10} more")

    return "\n".join(lines)


def auto_configure_service(data: dict) -> str:
    """Save credentials for a service and test the connection."""
    from familiar.channels.connect_wizard.auto_setup import AutoSetupEngine
    from familiar.channels.connect_wizard.service_catalog import SERVICE_CATALOG

    service = data.get("service", "").strip()
    credentials = data.get("credentials", {})

    if not service:
        return "Error: 'service' is required (e.g. 'todoist', 'stripe')"

    entry = SERVICE_CATALOG.get(service)
    if entry is None:
        available = ", ".join(sorted(SERVICE_CATALOG.keys()))
        return f"Error: Unknown service '{service}'. Available: {available}"

    if not credentials:
        # Build hint about what env vars are needed
        if entry.env_vars:
            vars_hint = ", ".join(entry.env_vars)
            return f"Error: 'credentials' required. Expected keys: {vars_hint}"
        return f"Error: {entry.display_name} doesn't use API credentials."

    engine = AutoSetupEngine()
    results = engine.apply_credentials({service: credentials})
    info = results.get(service, {})

    if not info.get("saved"):
        return f"Error saving {entry.display_name}: {info.get('error', 'unknown error')}"

    # Test
    ok, msg = engine.test_service(service)
    if ok:
        return f"{entry.display_name} configured and connected! {msg}"
    else:
        return f"{entry.display_name} saved but test failed: {msg}"


TOOLS = [
    {
        "name": "check_setup_status",
        "description": (
            "Check which services are configured, which are recommended but "
            "missing, and overall setup status. Optionally pass a job_class "
            "(helper, social_worker, business_buddy, nonprofit_director, chef, "
            "artist) to see role-specific recommendations."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "job_class": {
                    "type": "string",
                    "description": "Optional job class for tailored recommendations",
                    "enum": [
                        "helper",
                        "social_worker",
                        "business_buddy",
                        "nonprofit_director",
                        "chef",
                        "artist",
                    ],
                },
            },
        },
        "handler": check_setup_status,
    },
    {
        "name": "auto_configure_service",
        "description": (
            "Save API credentials for a service and test the connection. "
            "Use when the user provides an API key in conversation."
        ),
        "input_schema": {
            "type": "object",
            "properties": {
                "service": {
                    "type": "string",
                    "description": "Service key (e.g. 'todoist', 'stripe', 'hubspot')",
                },
                "credentials": {
                    "type": "object",
                    "description": (
                        'Map of env var name to value, e.g. {"TODOIST_API_TOKEN": "abc123"}'
                    ),
                },
            },
            "required": ["service", "credentials"],
        },
        "handler": auto_configure_service,
    },
]
