package main

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
)

type rpcRequest struct {
	JSONRPC string          `json:"jsonrpc"`
	ID      string          `json:"id"`
	Method  string          `json:"method"`
	Params  json.RawMessage `json:"params"`
}

type rpcResponse struct {
	JSONRPC string    `json:"jsonrpc"`
	ID      string    `json:"id"`
	Result  any       `json:"result,omitempty"`
	Error   *rpcError `json:"error,omitempty"`
}

type rpcError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

type smsSendRequest struct {
	Phone        string         `json:"phone"`
	Code         string         `json:"code"`
	Purpose      string         `json:"purpose"`
	TemplateCode string         `json:"template_code"`
	Config       map[string]any `json:"config"`
}

func main() {
	raw, err := io.ReadAll(os.Stdin)
	if err != nil {
		writeError("", -32700, err.Error())
		return
	}
	var req rpcRequest
	if err := json.Unmarshal(raw, &req); err != nil {
		writeError("", -32700, err.Error())
		return
	}
	switch req.Method {
	case "sms.send":
		var params smsSendRequest
		if err := json.Unmarshal(req.Params, &params); err != nil {
			writeError(req.ID, -32602, err.Error())
			return
		}
		writeOK(req.ID, map[string]any{
			"ok":         true,
			"provider":   "sms-echo",
			"message_id": fmt.Sprintf("echo-%s-%s", params.Purpose, params.Phone),
		})
	default:
		writeError(req.ID, -32601, "method not found")
	}
}

func writeOK(id string, result any) {
	_ = json.NewEncoder(os.Stdout).Encode(rpcResponse{JSONRPC: "2.0", ID: id, Result: result})
}

func writeError(id string, code int, message string) {
	_ = json.NewEncoder(os.Stdout).Encode(rpcResponse{JSONRPC: "2.0", ID: id, Error: &rpcError{Code: code, Message: message}})
}
