# 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

"""
KoboToolbox Intake Forms Skill

List forms, view submissions, and export data for social worker case management.

Setup:
    KOBO_URL=https://kf.kobotoolbox.org  (or your self-hosted instance)
    KOBO_TOKEN=your_api_token

Get a token at: Account Settings > Security > API Key
API: https://[server]/api/v2/
"""

import logging

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

logger = logging.getLogger(__name__)


def _token() -> str:
    return get_env("KOBO_TOKEN") or ""


def _base_url() -> str:
    return (get_env("KOBO_URL") or "https://kf.kobotoolbox.org").rstrip("/")


def _headers() -> dict:
    return {"Authorization": f"Token {_token()}"}


def _check_config() -> str:
    if not _token():
        return (
            "KoboToolbox not configured.\n"
            "Set KOBO_TOKEN in your environment.\n"
            "Get a token at: Account Settings > Security > API Key"
        )
    return ""


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


def kobo_forms(data: dict) -> str:
    """List KoboToolbox forms/assets."""
    err = _check_config()
    if err:
        return err

    limit = min(int(data.get("limit", 20)), 100)

    try:
        result = _forms_cached(limit)

        forms = result.get("results", [])
        if not forms:
            return "No forms found."

        total = result.get("count", len(forms))
        lines = [f"**Forms** ({len(forms)} of {total}):", ""]

        for i, f in enumerate(forms, 1):
            name = f.get("name", "Untitled")
            uid = f.get("uid", "")
            date_mod = f.get("date_modified", "")[:10]
            owner = f.get("owner", "")
            deployment = f.get("deployment__active", False)
            status = "Active" if deployment else "Draft"

            lines.append(f"{i}. **{name}** [{status}]")
            details = [f"UID: {uid}"]
            if date_mod:
                details.append(f"Modified: {date_mod}")
            if owner:
                details.append(f"Owner: {owner}")
            lines.append(f"   {' | '.join(details)}")
            lines.append("")

        return "\n".join(lines)

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


@cached(prefix="kobo_forms", ttl=120)
def _forms_cached(limit: int) -> dict:
    return api_get(
        f"{_base_url()}/api/v2/assets/",
        params={"format": "json", "limit": limit},
        headers=_headers(),
        service_name="KoboToolbox",
    )


def kobo_submissions(data: dict) -> str:
    """View form submissions."""
    err = _check_config()
    if err:
        return err

    asset_uid = data.get("asset_uid", "").strip()
    if not asset_uid:
        return "Please provide an asset_uid (form ID)."

    limit = min(int(data.get("limit", 20)), 100)

    try:
        result = _submissions_cached(asset_uid, limit)

        submissions = result.get("results", [])
        if not submissions:
            return "No submissions found for this form."

        total = result.get("count", len(submissions))
        lines = [f"**Submissions** ({len(submissions)} of {total}):", ""]

        for i, s in enumerate(submissions, 1):
            sub_id = s.get("_id", "")
            sub_time = s.get("_submission_time", "")[:16]
            submitted_by = s.get("_submitted_by", "")

            lines.append(f"{i}. **Submission #{sub_id}**")
            details = []
            if sub_time:
                details.append(f"Time: {sub_time}")
            if submitted_by:
                details.append(f"By: {submitted_by}")
            if details:
                lines.append(f"   {' | '.join(details)}")

            field_lines = []
            for key, val in s.items():
                if key.startswith("_") or not val:
                    continue
                val_str = str(val)[:80]
                field_lines.append(f"   {key}: {val_str}")
            lines.extend(field_lines[:6])
            lines.append("")

        return "\n".join(lines)

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


@cached(prefix="kobo_submissions", ttl=60)
def _submissions_cached(asset_uid: str, limit: int) -> dict:
    return api_get(
        f"{_base_url()}/api/v2/assets/{asset_uid}/data/",
        params={"format": "json", "limit": limit},
        headers=_headers(),
        service_name="KoboToolbox",
    )


def kobo_form_stats(data: dict) -> str:
    """Get form statistics (submission count, dates)."""
    err = _check_config()
    if err:
        return err

    asset_uid = data.get("asset_uid", "").strip()
    if not asset_uid:
        return "Please provide an asset_uid (form ID)."

    try:
        result = _form_detail_cached(asset_uid)

        name = result.get("name", "Untitled")
        uid = result.get("uid", "")
        owner = result.get("owner", "")
        date_created = result.get("date_created", "")[:10]
        date_mod = result.get("date_modified", "")[:10]
        deployment = result.get("deployment__active", False)
        sub_count = result.get("deployment__submission_count", 0)

        lines = [
            f"**{name}**",
            "",
            f"  UID: {uid}",
            f"  Owner: {owner}",
            f"  Status: {'Active' if deployment else 'Draft'}",
            f"  Submissions: {sub_count}",
            f"  Created: {date_created}",
            f"  Modified: {date_mod}",
        ]

        return "\n".join(lines)

    except APIError as e:
        return str(e)
    except Exception as e:
        logger.error("KoboToolbox form stats error: %s", e)
        return f"Error fetching form stats: {e}"


@cached(prefix="kobo_form_detail", ttl=120)
def _form_detail_cached(asset_uid: str) -> dict:
    return api_get(
        f"{_base_url()}/api/v2/assets/{asset_uid}/",
        params={"format": "json"},
        headers=_headers(),
        service_name="KoboToolbox",
    )


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

TOOLS = [
    {
        "name": "kobo_forms",
        "description": "List KoboToolbox forms with status, owner, and modification date.",
        "input_schema": {
            "type": "object",
            "properties": {
                "limit": {
                    "type": "integer",
                    "description": "Max results (1-100, default 20)",
                    "default": 20,
                },
            },
        },
        "handler": kobo_forms,
        "category": "kobo",
    },
    {
        "name": "kobo_submissions",
        "description": "View submissions for a KoboToolbox form with field data.",
        "input_schema": {
            "type": "object",
            "properties": {
                "asset_uid": {
                    "type": "string",
                    "description": "Form UID (from kobo_forms)",
                },
                "limit": {
                    "type": "integer",
                    "description": "Max results (1-100, default 20)",
                    "default": 20,
                },
            },
            "required": ["asset_uid"],
        },
        "handler": kobo_submissions,
        "category": "kobo",
    },
    {
        "name": "kobo_form_stats",
        "description": "Get KoboToolbox form statistics: submission count, dates, status.",
        "input_schema": {
            "type": "object",
            "properties": {
                "asset_uid": {
                    "type": "string",
                    "description": "Form UID (from kobo_forms)",
                },
            },
            "required": ["asset_uid"],
        },
        "handler": kobo_form_stats,
        "category": "kobo",
    },
]
