"""API endpoints for tools information."""

import json
from pathlib import Path
from typing import Any

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel

import mindroom
from mindroom.credentials import CredentialsManager, get_credentials_manager

from .google_tools_helper import check_google_tool_configured

router = APIRouter(prefix="/api/tools", tags=["tools"])


class ToolsResponse(BaseModel):
    """Response containing all registered tools."""

    tools: list[dict]


def _check_homeassistant_configured(tool_name: str, manager: CredentialsManager) -> bool:
    """Check if HomeAssistant is configured."""
    if tool_name == "homeassistant":
        ha_creds = manager.load_credentials("homeassistant")
        if not ha_creds:
            return False
        # Check for the fields that HomeAssistantTools actually uses
        has_url = "instance_url" in ha_creds
        has_token = "access_token" in ha_creds or "long_lived_token" in ha_creds
        return has_url and has_token
    return False


def _check_standard_tool_configured(tool: dict[str, Any], manager: CredentialsManager) -> bool:
    """Check if a standard tool with config_fields is configured."""
    if not tool.get("config_fields"):
        return False

    credentials = manager.load_credentials(tool["name"])
    if not credentials:
        return False

    # Check if all required fields are present
    required_fields = [field["name"] for field in tool.get("config_fields", []) if field.get("required", True)]
    return all(field in credentials for field in required_fields)


@router.get("")
async def get_registered_tools() -> ToolsResponse:
    """Get all registered tools from mindroom.

    This reads from a pre-generated JSON file that is created by the test suite.
    The JSON file is generated by tests/test_tools_metadata.py and committed to the repo.
    It also checks if credentials exist for tools that require them.
    """
    # Path to the generated JSON file - use package location for reliability
    package_dir = Path(mindroom.__file__).parent
    json_path = package_dir / "tools_metadata.json"

    if not json_path.exists():
        raise HTTPException(
            status_code=500,
            detail="tools_metadata.json not found. Run 'pytest tests/test_tools_metadata.py' to generate it.",
        )

    with json_path.open() as f:
        data = json.load(f)
        tools = data["tools"]

    # Get credentials manager to check if tools are configured
    manager = get_credentials_manager()

    # Update status for tools that require configuration
    for tool in tools:
        tool_name = tool["name"]
        if tool.get("status") == "requires_config":
            # Check if tool has delegated auth
            auth_provider = tool.get("auth_provider")
            if auth_provider:
                # Check if the auth provider is configured
                provider_creds = manager.load_credentials(auth_provider)
                if provider_creds and (
                    (auth_provider == "google" and check_google_tool_configured(tool_name, provider_creds))
                    or auth_provider != "google"
                ):
                    tool["status"] = "available"
            # Check other configured tools
            elif _check_homeassistant_configured(tool_name, manager) or _check_standard_tool_configured(tool, manager):
                tool["status"] = "available"

    return ToolsResponse(tools=tools)
