"""MCP Server (HTTP proxy) for ISellMore Translations management.

Connects to the remote Flask Translations site via REST API.
No direct database access — all operations go through HTTP endpoints.
This allows the MCP server to run locally while the site runs on a remote server.

Requirements:
    pip install "mcp[cli]" httpx
"""
import json
import os

import httpx
from mcp.server.fastmcp import FastMCP

API_BASE_URL = os.environ.get("TRANSLATIONS_API_URL", "http://192.168.14.241:5050")

mcp = FastMCP("Translations ISellMore")


def _api_get(path: str, params: dict = None) -> httpx.Response:
    """Send GET request to the Translations API."""
    return httpx.get(f"{API_BASE_URL}{path}", params=params, timeout=30)


def _api_post_json(path: str, payload: dict) -> httpx.Response:
    """Send POST request with JSON body to the Translations API."""
    return httpx.post(f"{API_BASE_URL}{path}", json=payload, timeout=30)


def _api_post_form(path: str, data: dict) -> httpx.Response:
    """Send POST request with form data to the Translations API."""
    return httpx.post(f"{API_BASE_URL}{path}", data=data, timeout=30)


# =========================================================================
# MCP Resources
# =========================================================================

@mcp.resource("translations://languages")
def resource_languages() -> str:
    """List of all enabled translation languages ordered by priority."""
    resp = _api_get("/api/plugin/languages")
    return resp.text


@mcp.resource("translations://config/environments")
def resource_environments() -> str:
    """Available deployment environments for translation promotion."""
    envs = [
        {"name": "DEV", "description": "Development environment"},
        {"name": "QATEST", "description": "QA Test environment"},
        {"name": "TEST", "description": "Test environment"},
        {"name": "RELEASE", "description": "Release / staging environment"},
        {"name": "PROD-UA", "description": "Production Ukraine"},
        {"name": "PROD-FL", "description": "Production FL"},
    ]
    return json.dumps(envs, ensure_ascii=False, indent=2)


# =========================================================================
# Read-only tools
# =========================================================================

@mcp.tool()
def search_translations(query: str, page: int = 1) -> str:
    """Search translation keys by query string with pagination (20 items per page).

    Returns a JSON object with matching keys and all their translation values.
    Use an empty string to browse all keys.
    """
    resp = _api_get("/api/search", params={"query": query, "page": page})
    if resp.status_code != 200:
        return json.dumps({"error": f"API returned {resp.status_code}", "detail": resp.text})
    return resp.text


@mcp.tool()
def get_translation(key: str) -> str:
    """Get full translation data for a specific key name, including all language values."""
    resp = _api_get(f"/api/plugin/translation/{key}")
    if resp.status_code == 404:
        return json.dumps({"error": f"Key '{key}' not found"})
    if resp.status_code != 200:
        return json.dumps({"error": f"API returned {resp.status_code}", "detail": resp.text})
    return resp.text


@mcp.tool()
def get_languages() -> str:
    """Get the ordered list of all enabled translation language codes."""
    resp = _api_get("/api/plugin/languages")
    return resp.text


@mcp.tool()
def get_route(key: str) -> str:
    """Get the route associated with a translation key."""
    resp = _api_get(f"/get_route/{key}")
    if resp.status_code != 200:
        return json.dumps({"error": f"API returned {resp.status_code}"})
    return json.dumps({"key": key, "route": resp.json()}, ensure_ascii=False)


# =========================================================================
# Write tools
# =========================================================================

@mcp.tool()
def create_key(
    key: str,
    value: str,
    language_key: str,
    route: str = "",
    is_custom: bool = False,
    is_format: bool = False,
) -> str:
    """Create a new translation key with automatic translation to all languages.

    Provide the value in one language (language_key) and the system will
    auto-translate to every other enabled language via Google Translate.
    If an existing key already has the same value, its translations are reused.

    Args:
        key: The translation key name (e.g. 'LOGIN_BUTTON')
        value: The text value in the source language
        language_key: Source language code (e.g. 'en', 'uk')
        route: Optional route/module path
        is_custom: Mark as custom key
        is_format: Mark as format key
    """
    payload = {
        "key": key,
        "route": route,
        "languageKey": language_key,
        "value": value,
        "isCustom": is_custom,
        "isFormat": is_format,
    }
    resp = _api_post_json("/create_key", payload)
    data = resp.json()
    success = resp.status_code == 200
    return json.dumps({"success": success, "message": data.get("message", "")})


@mcp.tool()
def update_translation_value(translation_id: int, new_value: str) -> str:
    """Update the text value of a specific translation entry.

    Args:
        translation_id: The ID of the translation map entry (TranslationID)
        new_value: The new text value
    """
    resp = _api_post_form(
        f"/update_value/{translation_id}",
        data={"new_value_value": new_value},
    )
    if resp.status_code != 200:
        return json.dumps({"success": False, "message": f"API returned {resp.status_code}"})
    return resp.text


@mcp.tool()
def update_key_name(key_id: int, new_name: str) -> str:
    """Rename a translation key.

    Args:
        key_id: The ID of the translation key
        new_name: The new key name
    """
    resp = _api_post_form(
        f"/update_key/{key_id}",
        data={"new_key_value": new_name},
    )
    if resp.status_code != 200:
        return json.dumps({"success": False, "message": f"API returned {resp.status_code}"})
    return resp.text


@mcp.tool()
def delete_key(key_id: int) -> str:
    """Delete a translation key and all its translation values.

    Args:
        key_id: The ID of the translation key to delete
    """
    resp = _api_post_form(f"/delete_key/{key_id}", data={})
    if resp.status_code != 200:
        return json.dumps({"success": False, "message": f"API returned {resp.status_code}"})
    return resp.text


# =========================================================================
# Promote tools
# =========================================================================

@mcp.tool()
def move_to_test(key_id: int) -> str:
    """Promote a translation key from DEV to TEST environments (QATEST + TEST).

    Args:
        key_id: The ID of the key to promote
    """
    resp = _api_post_form(f"/move_to_test/{key_id}", data={})
    if resp.status_code != 200:
        return json.dumps({"success": False, "message": f"API returned {resp.status_code}"})
    return resp.text


@mcp.tool()
def move_to_release(key_id: int) -> str:
    """Promote a translation key from DEV to RELEASE environment.

    Args:
        key_id: The ID of the key to promote
    """
    resp = _api_post_form(f"/move_to_release/{key_id}", data={})
    if resp.status_code != 200:
        return json.dumps({"success": False, "message": f"API returned {resp.status_code}"})
    return resp.text


@mcp.tool()
def move_to_prod(key_id: int) -> str:
    """Promote a translation key to PRODUCTION environments (UA + FL).

    WARNING: This pushes changes to live production servers.

    Args:
        key_id: The ID of the key to promote
    """
    resp = _api_post_form(f"/move_to_prod/{key_id}", data={})
    if resp.status_code != 200:
        return json.dumps({"success": False, "message": f"API returned {resp.status_code}"})
    return resp.text


# =========================================================================
# Entry point
# =========================================================================

if __name__ == "__main__":
    mcp.run(transport="stdio")
