from __future__ import annotations

import json
import sys
from typing import Any

from app.core.postgres.erp_client import ErpDatabaseClient
from app.modules.financial.application.four_pillars_service import FourPillarsService

from .tool_dispatcher import ToolDispatcherMixin
from .tools_registry import SERVER_NAME, SERVER_VERSION, TOOLS_DEFINITION


class DSConsMCPServer(ToolDispatcherMixin):
    """Standard JSON-RPC 2.0 MCP Server handler for DeepSeek Harness (DSH)."""

    def __init__(self) -> None:
        self.postgres_client = ErpDatabaseClient()
        self.four_pillars = FourPillarsService(self.postgres_client)

    def handle_request(self, request: dict[str, Any]) -> dict[str, Any]:
        """Xử lý yêu cầu JSON-RPC từ MCP client (DSH / Claude / Antigravity)."""
        method = request.get("method")
        msg_id = request.get("id")

        if method == "initialize":
            return {
                "jsonrpc": "2.0",
                "id": msg_id,
                "result": {
                    "protocolVersion": "2024-11-05",
                    "serverInfo": {"name": SERVER_NAME, "version": SERVER_VERSION},
                    "capabilities": {"tools": {}},
                },
            }

        elif method == "tools/list":
            return {
                "jsonrpc": "2.0",
                "id": msg_id,
                "result": {"tools": TOOLS_DEFINITION},
            }

        elif method == "tools/call":
            params = request.get("params", {})
            name = params.get("name")
            args = params.get("arguments", {})

            try:
                content = self._execute_tool(name, args)
                return {
                    "jsonrpc": "2.0",
                    "id": msg_id,
                    "result": {
                        "content": [
                            {
                                "type": "text",
                                "text": json.dumps(
                                    content, ensure_ascii=False, indent=2, default=str
                                ),
                            }
                        ],
                        "isError": False,
                    },
                }
            except Exception as exc:
                return {
                    "jsonrpc": "2.0",
                    "id": msg_id,
                    "result": {
                        "content": [
                            {
                                "type": "text",
                                "text": f"Lỗi thực thi tool {name}: {exc!s}",
                            }
                        ],
                        "isError": True,
                    },
                }

        else:
            return {
                "jsonrpc": "2.0",
                "id": msg_id,
                "error": {"code": -32601, "message": f"Method not found: {method}"},
            }


def run_stdio_server():
    """Vòng lặp đọc JSON-RPC từ stdin và ghi stdout cho DeepSeek Harness (DSH)."""
    server = DSConsMCPServer()
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            req = json.loads(line)
            res = server.handle_request(req)
            sys.stdout.write(json.dumps(res, ensure_ascii=False) + "\n")
            sys.stdout.flush()
        except Exception as exc:
            err_res = {
                "jsonrpc": "2.0",
                "id": None,
                "error": {"code": -32700, "message": f"Parse error: {exc!s}"},
            }
            sys.stdout.write(json.dumps(err_res) + "\n")
            sys.stdout.flush()
