# 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

"""
Jitsi Meet Video Conferencing Skill

Generate meeting links and optionally create JWT-authenticated rooms.

Setup (minimal):
    JITSI_URL=https://meet.jit.si  (or your self-hosted instance)

Optional (self-hosted with JWT):
    JITSI_APP_ID=your_app_id
    JITSI_APP_SECRET=your_shared_secret

Docs: https://jitsi.github.io/handbook/
"""

import hashlib
import logging
import time
import uuid

from familiar.skills._api_utils import get_env

logger = logging.getLogger(__name__)


def _jitsi_url() -> str:
    return (get_env("JITSI_URL") or "https://meet.jit.si").rstrip("/")


def _app_id() -> str:
    return get_env("JITSI_APP_ID") or ""


def _app_secret() -> str:
    return get_env("JITSI_APP_SECRET") or ""


def _jwt_enabled() -> bool:
    return bool(_app_id() and _app_secret())


def _generate_room_name(topic: str) -> str:
    """Generate a URL-safe room name from a topic."""
    safe = "".join(c if c.isalnum() or c in "-_" else "-" for c in topic.lower())
    safe = safe.strip("-")
    if not safe:
        safe = "meeting"
    short_hash = hashlib.md5(f"{safe}{time.time()}".encode()).hexdigest()[:6]
    return f"{safe}-{short_hash}"


def _generate_jwt(room: str, user_name: str, moderator: bool) -> str:
    """Generate a JWT token for a Jitsi room."""
    try:
        import jwt as pyjwt
    except ImportError:
        return ""

    domain = _jitsi_url().split("//")[-1]
    payload = {
        "iss": _app_id(),
        "sub": domain,
        "room": room,
        "aud": "jitsi",
        "exp": int(time.time()) + 900,
        "context": {
            "user": {
                "name": user_name or "Participant",
                "id": str(uuid.uuid4())[:8],
            }
        },
    }
    if moderator:
        payload["context"]["user"]["affiliation"] = "owner"

    return pyjwt.encode(payload, _app_secret(), algorithm="HS256")


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


def create_meeting_link(data: dict) -> str:
    """Generate a Jitsi meeting link."""
    topic = data.get("topic", "").strip()
    room_name = data.get("room_name", "").strip()
    moderator = data.get("moderator", False)
    user_name = data.get("user_name", "").strip()

    if not room_name:
        room_name = _generate_room_name(topic or "meeting")

    base = _jitsi_url()
    url = f"{base}/{room_name}"

    lines = ["**Meeting link created!**", ""]

    if _jwt_enabled():
        token = _generate_jwt(room_name, user_name, moderator)
        if token:
            url = f"{url}?jwt={token}"
            lines.append(f"  Mode: {'Moderator' if moderator else 'Participant'}")
            lines.append("  Auth: JWT token (expires in 15 min)")

    lines.insert(2, f"  URL: {url}")
    if topic:
        lines.append(f"  Topic: {topic}")
    lines.append(f"  Room: {room_name}")

    return "\n".join(lines)


def jitsi_status(data: dict) -> str:
    """Show Jitsi configuration status."""
    base = _jitsi_url()
    jwt = _jwt_enabled()

    lines = [
        "**Jitsi Meet Status**",
        "",
        f"  Server: {base}",
        f"  JWT Auth: {'Enabled' if jwt else 'Disabled (public rooms)'}",
    ]

    if base == "https://meet.jit.si":
        lines.append("  Instance: Public (meet.jit.si)")
    else:
        lines.append("  Instance: Self-hosted")

    if jwt:
        lines.append(f"  App ID: {_app_id()}")

    return "\n".join(lines)


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

TOOLS = [
    {
        "name": "create_meeting_link",
        "description": "Generate a Jitsi Meet video conference link with optional JWT auth.",
        "input_schema": {
            "type": "object",
            "properties": {
                "topic": {
                    "type": "string",
                    "description": "Meeting topic (used for room name generation)",
                },
                "room_name": {
                    "type": "string",
                    "description": "Custom room name (auto-generated if omitted)",
                },
                "moderator": {
                    "type": "boolean",
                    "description": "Generate moderator token (JWT only)",
                    "default": False,
                },
                "user_name": {
                    "type": "string",
                    "description": "Display name in the meeting",
                },
            },
        },
        "handler": create_meeting_link,
        "category": "jitsi",
    },
    {
        "name": "jitsi_status",
        "description": "Show Jitsi Meet server configuration and auth status.",
        "input_schema": {"type": "object", "properties": {}},
        "handler": jitsi_status,
        "category": "jitsi",
    },
]
