# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# Licensed under the MIT License

"""Skills routes — extracted from memory.py."""

from __future__ import annotations

import json
import logging
import os
import threading
from datetime import datetime
from pathlib import Path

from flask import Blueprint, Response, jsonify, request, send_file

from ..auth import require_auth
from ..helpers import get_agent, get_service_manager, get_marketplace_catalog, DATA_DIR

logger = logging.getLogger(__name__)

bp = Blueprint("skills", __name__)


@bp.route("/api/skills")
@require_auth
def api_skills():
    """Get loaded skills with prerequisite status."""
    agent = get_agent()
    from familiar.core.skills import check_skill_prerequisites

    prereq_failures = check_skill_prerequisites()
    skills = []
    for s in agent.skills.list_skills():
        name = s["name"]
        failures = prereq_failures.get(name, [])
        if s["enabled"] and not failures:
            status = "connected"
        elif failures:
            status = "setup_required"
        else:
            status = "optional"
        skills.append(
            {
                **s,
                "configured": s["enabled"] and not failures,
                "status": status,
                "tools_count": len(s.get("tools", [])),
                "setup_command": f"/connect {name}",
                "prerequisites": failures,
            }
        )
    return jsonify({"skills": skills})


@bp.route("/api/skills/<name>/detail")
@require_auth
def api_skill_detail(name):
    """Get full SKILL.md content for a skill."""
    agent = get_agent()
    skill = agent.skills.get_skill(name)
    if not skill:
        return jsonify({"error": "Skill not found"}), 404

    from familiar.core.skills import check_skill_prerequisites

    prereq_failures = check_skill_prerequisites()
    failures = prereq_failures.get(name, [])
    configured = skill.enabled and not failures

    return jsonify(
        {
            "name": name,
            "description": skill.description,
            "summary": skill.summary,
            "tools": [t.name for t in skill.tools],
            "configured": configured,
            "setup_command": f"/connect {name}",
            "prerequisites": failures,
            "enabled": skill.enabled,
        }
    )


@bp.route("/api/skills/<name>/toggle", methods=["POST"])
@require_auth
def api_skill_toggle(name):
    """Enable/disable a skill."""
    agent = get_agent()
    skill = agent.skills.get_skill(name)

    if not skill:
        return jsonify({"error": "Skill not found"}), 404

    if skill.enabled:
        agent.skills.disable_skill(name)
        return jsonify({"enabled": False})
    else:
        agent.skills.enable_skill(name)
        return jsonify({"enabled": True})


@bp.route("/api/tools")
@require_auth
def api_tools():
    """Get available tools."""
    agent = get_agent()
    tools = []

    for tool in agent.tools.get_all():
        tools.append(
            {"name": tool.name, "description": tool.description, "category": tool.category}
        )

    return jsonify({"tools": tools})


